Additive primes: Difference between revisions

Added C++ and Forth solutions
(Added C++ and Forth solutions)
Line 26:
<pre>2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151 157 173 179 191 193 197 199 223 227 229 241 263 269 281 283
311 313 317 331 337 353 359 373 379 397 401 409 421 443 449 461 463 467 487</pre>
 
=={{header|C++}}==
<lang cpp>#include <iomanip>
#include <iostream>
 
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
 
unsigned int digit_sum(unsigned int n) {
unsigned int sum = 0;
for (; n > 0; n /= 10)
sum += n % 10;
return sum;
}
 
int main() {
const unsigned int limit = 500;
std::cout << "Additive primes less than " << limit << ":\n";
unsigned int count = 0;
for (unsigned int n = 1; n < limit; ++n) {
if (is_prime(digit_sum(n)) && is_prime(n)) {
std::cout << std::setw(3) << n;
if (++count % 10 == 0)
std::cout << '\n';
else
std::cout << ' ';
}
}
std::cout << '\n' << count << " additive primes found.\n";
}</lang>
 
{{out}}
<pre>
Additive primes less than 500:
2 3 5 7 11 23 29 41 43 47
61 67 83 89 101 113 131 137 139 151
157 173 179 191 193 197 199 223 227 229
241 263 269 281 283 311 313 317 331 337
353 359 373 379 397 401 409 421 443 449
461 463 467 487
54 additive primes found.
</pre>
 
=={{header|Factor}}==
Line 48 ⟶ 104:
 
Found 54 additive primes < 500.
</pre>
 
=={{header|Forth}}==
{{works with|Gforth}}
<lang forth>: 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 ( n -- n )
0 >r
begin
dup 0 >
while
dup 10 mod r> + >r
10 /
repeat
drop r> ;
 
: 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</lang>
 
{{out}}
<pre>
Additive primes less than 500:
2 3 5 7 11 23 29 41 43 47
61 67 83 89 101 113 131 137 139 151
157 173 179 191 193 197 199 223 227 229
241 263 269 281 283 311 313 317 331 337
353 359 373 379 397 401 409 421 443 449
461 463 467 487
54 additive primes found.
</pre>
 
1,777

edits