How to resolve the algorithm Additive primes step by step in the Forth programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Additive primes step by step in the Forth programming language

Table of Contents

Problem Statement

In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.

Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Additive primes step by step in the Forth programming language

Source code in the forth programming language

: prime? ( n -- ? ) here + c@ 0= ;
: notprime! ( n -- ) here + 1 swap c! ;

: prime_sieve ( n -- )
  here over erase
  0 notprime!
  1 notprime!
  2
  begin
    2dup dup * >
  while
    dup prime? if
      2dup dup * do
        i notprime!
      dup +loop
    then
    1+
  repeat
  2drop ;

: digit_sum ( u -- u )
  dup 10 < if exit then
  10 /mod recurse + ;

: print_additive_primes ( n -- )
  ." Additive primes less than " dup 1 .r ." :" cr
  dup prime_sieve
  0 swap
  1 do
    i prime? if
      i digit_sum prime? if
        i 3 .r
        1+ dup 10 mod 0= if cr else space then
      then
    then
  loop
  cr . ." additive primes found." cr ;

500 print_additive_primes
bye


  

You may also check:How to resolve the algorithm IBAN step by step in the Go programming language
You may also check:How to resolve the algorithm Array concatenation step by step in the VBA programming language
You may also check:How to resolve the algorithm ABC problem step by step in the Ela programming language
You may also check:How to resolve the algorithm Five weekends step by step in the Phix programming language
You may also check:How to resolve the algorithm Inheritance/Multiple step by step in the Raku programming language