Additive primes: Difference between revisions

m
→‎{{header|ALGOL 68}}: Avoid line wrap
No edit summary
m (→‎{{header|ALGOL 68}}: Avoid line wrap)
(40 intermediate revisions by 23 users not shown)
Line 21:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F is_prime(a)
I a == 2
R 1B
Line 43:
additive_primes++
print(i, end' ‘ ’)
print("\nFound "additive_primes‘ additive primes less than 500’)</langsyntaxhighlight>
 
{{out}}
Line 52:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program additivePrime64.s */
Line 202:
.include "../includeARM64.inc"
 
</syntaxhighlight>
</lang>
<pre>
Prime : 2
Line 260:
Number found : 54
</pre>
=={{header|ABC}}==
<syntaxhighlight lang="abc">HOW TO REPORT prime n:
REPORT n>=2 AND NO d IN {2..floor root n} HAS n mod d = 0
 
HOW TO RETURN digit.sum n:
SELECT:
n<10: RETURN n
ELSE: RETURN (n mod 10) + digit.sum floor (n/10)
 
HOW TO REPORT additive.prime n:
REPORT prime n AND prime digit.sum n
 
PUT 0 IN n
FOR i IN {1..499}:
IF additive.prime i:
WRITE i>>4
PUT n+1 IN n
IF n mod 10 = 0: WRITE /
 
WRITE /
WRITE "There are `n` additive primes less than 500."/</syntaxhighlight>
{{out}}
<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
There are 54 additive primes less than 500.</pre>
 
=={{header|Action!}}==
{{libheader|Action! Sieve of Eratosthenes}}
<syntaxhighlight lang="action!">
;;; find some additive primes - primes whose digit sum is also prime
;;; Library: Action! Sieve of Eratosthenes
INCLUDE "H6:SIEVE.ACT"
 
PROC Main()
DEFINE MAX_PRIME = "500"
 
BYTE ARRAY primes(MAX_PRIME)
CARD n, digitSum, v, count
Sieve(primes,MAX_PRIME)
 
count = 0
FOR n = 1 TO MAX_PRIME - 1 DO
IF primes( n ) THEN
digitSum = 0
v = n
WHILE v > 0 DO
digitSum ==+ v MOD 10
v ==/ 10
OD
IF primes( digitSum ) THEN
IF n < 100 THEN
Put(' )
IF n < 10 THEN Put(' ) FI
FI
Put(' )PrintI( n )
count ==+ 1
IF count MOD 20 = 0 THEN PutE() FI
FI
FI
OD
PutE()Print( "Found " )PrintI( count )Print( " additive primes below " )PrintI( MAX_PRIME + 1 )PutE()
RETURN
</syntaxhighlight>
{{out}}
<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
Found 54 additive primes below 501
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_Io;
 
procedure Additive_Primes is
Line 318 ⟶ 394:
Put (" additive primes.");
New_Line;
end Additive_Primes;</langsyntaxhighlight>
{{out}}
<pre>Additive primes <500:
Line 330 ⟶ 406:
=={{header|ALGOL 68}}==
{{libheader|ALGOL 68-primes}}
<langsyntaxhighlight lang="algol68">BEGIN # find additive primes - primes whose digit sum is also prime #
# sieve the primes to max prime #
PR read "primes.incl.a68" PR
Line 352 ⟶ 428:
FI
OD;
print( ( newline, "Found ", whole( additive count, 0 ), " additive primes below ", whole( UPB prime + 1, 0 ), newline ) );
print( ( " additive primes below ", whole( UPB prime + 1, 0 ), newline ) )
END</lang>
END</syntaxhighlight>
{{out}}
<pre>
Line 363 ⟶ 440:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin % find some additive primes - primes whose digit sum is also prime %
% sets p( 1 :: n ) to a sieve of primes up to n %
procedure Eratosthenes ( logical array p( * ) ; integer value n ) ;
Line 402 ⟶ 479:
write( i_w := 1, s_w := 0, "Found ", aCount, " additive primes below ", MAX_NUMBER )
end
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 413 ⟶ 490:
=={{header|APL}}==
 
<langsyntaxhighlight APLlang="apl">((+⌿(4/10)⊤P)∊P)/P←(~P∊P∘.×P)/P←1↓⍳500</langsyntaxhighlight>
 
{{out}}
Line 421 ⟶ 498:
 
=={{header|AppleScript}}==
<langsyntaxhighlight lang="applescript">on sieveOfEratosthenes(limit)
script o
property numberList : {missing value}
Line 466 ⟶ 543:
 
-- Task code:
tell additivePrimes(499) to return {|additivePrimes<500|:it, numberThereof:count}</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight lang="applescript">{|additivePrimes<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}, numberThereof:54}</langsyntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program additivePrime.s */
Line 618 ⟶ 695:
.include "../affichage.inc"
 
</syntaxhighlight>
</lang>
<pre>
Prime : 2
Line 678 ⟶ 755:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">additives: select 2..500 'x -> and? prime? x prime? sum digits x
 
loop split.every:10 additives 'a ->
print map a => [pad to :string & 4]
 
print ["\nFound" size additives "additive primes up to 500"]</langsyntaxhighlight>
 
{{out}}
Line 697 ⟶ 774:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f ADDITIVE_PRIMES.AWK
BEGIN {
Line 727 ⟶ 804:
return(sum)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 740 ⟶ 817:
 
=={{header|BASIC}}==
<langsyntaxhighlight lang="basic">10 DEFINT A-Z: E=500
20 DIM P(E): P(0)=-1: P(1)=-1
30 FOR I=2 TO SQR(E)
Line 750 ⟶ 827:
90 IF NOT P(S) THEN N=N+1: PRINT I,
100 NEXT
110 PRINT: PRINT N;" additive primes found below ";E</langsyntaxhighlight>
{{out}}
<pre> 2 3 5 7 11
Line 765 ⟶ 842:
54 additive primes found below 500</pre>
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight lang="gwbasic"> 0 E = 500
1 F = E - 1:L = LEN ( STR$ (F)) + 1: FOR I = 2 TO L:S$ = S$ + CHR$ (32): NEXT I: DIM P(E):P(0) = - 1:P(1) = - 1: FOR I = 2 TO SQR (F): IF NOT P(I) THEN FOR J = I * 2 TO E STEP I:P(J) = - 1: NEXT J
2 NEXT I: FOR I = B TO F: IF NOT P(I) THEN GOSUB 4
Line 771 ⟶ 848:
4 S = 0: IF I THEN FOR J = I TO 0 STEP 0:J1 = INT (J / 10):S = S + (J - J1 * 10):J = J1: NEXT J
5 IF NOT P(S) THEN N = N + 1: PRINT RIGHT$ (S$ + STR$ (I),L);
6 RETURN</langsyntaxhighlight>
<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
Line 777 ⟶ 854:
</pre>
 
==={{header|BASIC256}}===
<langsyntaxhighlight lang="freebasic">print "Prime", "Digit Sum"
for i = 2 to 499
if isprime(i) then
Line 805 ⟶ 882:
end while
return s
end function</langsyntaxhighlight>
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
manifest $( limit = 500 $)
 
Line 842 ⟶ 919:
$)
writef("*N*NFound %N additive primes < %N.*N", num, limit)
$)</langsyntaxhighlight>
{{out}}
<pre> 2 3 5 7 11 23 29 41 43 47
Line 854 ⟶ 931:
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang C>
#include <stdbool.h>
#include <stdio.h>
Line 928 ⟶ 1,005:
return 0;
}/* main */
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 942 ⟶ 1,019:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
 
Line 983 ⟶ 1,060:
}
std::cout << '\n' << count << " additive primes found.\n";
}</langsyntaxhighlight>
 
{{out}}
Line 999 ⟶ 1,076:
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">% Sieve of Erastothenes
% Returns an array [1..max] marking the primes
sieve = proc (max: int) returns (array[bool])
Line 1,041 ⟶ 1,118:
stream$putl(po, "\nFound " || int$unparse(count) ||
" additive primes < " || int$unparse(max))
end start_up</langsyntaxhighlight>
{{out}}
<pre> 2 3 5 7 11 23 29 41 43 47
Line 1,052 ⟶ 1,129:
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. ADDITIVE-PRIMES.
Line 1,124 ⟶ 1,201:
SIEVE-INNER-LOOP.
MOVE 'X' TO COMPOSITE-FLAG(SIEVE-COMP).</langsyntaxhighlight>
{{out}}
<pre> 2 3 5 7 11 23 29 41 43 47
Line 1,136 ⟶ 1,213:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">
(defun sum-of-digits (n)
"Return the sum of the digits of a number"
Line 1,158 ⟶ 1,235:
 
 
</syntaxhighlight>
</lang>
{{out}}<pre>(dotimes (i 500) (when (additive-primep i) (princ i) (princ " ")))
 
Line 1,165 ⟶ 1,242:
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="ruby"># Fast/simple way to generate primes for small values.
# Uses P3 Prime Generator (PG) and its Prime Generator Sequence (PGS).
 
Line 1,203 ⟶ 1,280:
addprimes.each_with_index { |n, idx| printf "%*d ", maxdigits, n; print "\n" if idx % 10 == 9 } # more efficient
puts "\n#{addprimes.size} additive primes below #{nn}."
</syntaxhighlight>
</lang>
{{out}}
<pre> 2 3 5 7 11 23 29 41 43 47
Line 1,248 ⟶ 1,325:
4889 4919 4931 4933 4937 4951 4973 4999
338 additive primes below 5000.
 
</pre>
 
=={{header|Dart}}==
<syntaxhighlight lang="dart">import 'dart:math';
 
void main() {
const limit = 500;
print('Additive primes less than $limit :');
int count = 0;
for (int n = 1; n < limit; ++n) {
if (isPrime(digit_sum(n)) && isPrime(n)) {
print(' $n');
++count;
}
}
print('$count additive primes found.');
}
 
bool isPrime(int n) {
if (n <= 1) return false;
if (n == 2) return true;
for (int i = 2; i <= sqrt(n); ++i) {
if (n % i == 0) return false;
}
return true;
}
 
int digit_sum(int n) {
int sum = 0;
for (int m = n; m > 0; m ~/= 10) sum += m % 10;
return sum;
}</syntaxhighlight>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
Many Rosette Code problems have similar operations. This problem was solved using subroutines that were written and used for other problems. Instead of packing all the operations in a single block of code, this example shows the advantage of breaking operations into separate modules that aids in code resuse.
 
<syntaxhighlight lang="Delphi">
{These routines would normally be in libraries but are shown here for clarity}
 
 
function IsPrime(N: int64): boolean;
{Fast, optimised prime test}
var I,Stop: int64;
begin
if (N = 2) or (N=3) then Result:=true
else if (n <= 1) or ((n mod 2) = 0) or ((n mod 3) = 0) then Result:= false
else
begin
I:=5;
Stop:=Trunc(sqrt(N+0.0));
Result:=False;
while I<=Stop do
begin
if ((N mod I) = 0) or ((N mod (I + 2)) = 0) then exit;
Inc(I,6);
end;
Result:=True;
end;
end;
 
 
function SumDigits(N: integer): integer;
{Sum the integers in a number}
var T: integer;
begin
Result:=0;
repeat
begin
T:=N mod 10;
N:=N div 10;
Result:=Result+T;
end
until N<1;
end;
 
 
 
 
 
procedure ShowDigitSumPrime(Memo: TMemo);
var N,Sum,Cnt: integer;
var NS,S: string;
begin
Cnt:=0;
S:='';
for N:=1 to 500-1 do
if IsPrime(N) then
begin
Sum:=SumDigits(N);
if IsPrime(Sum) then
begin
Inc(Cnt);
S:=S+Format('%6d',[N]);
if (Cnt mod 8)=0 then S:=S+CRLF;
end;
end;
Memo.Lines.Add(S);
Memo.Lines.Add('Count = '+IntToStr(Cnt));
end;
 
 
</syntaxhighlight>
{{out}}
<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
Count = 54
Elapsed Time: 2.812 ms.
 
</pre>
Line 1,255 ⟶ 1,448:
 
=={{header|Draco}}==
<langsyntaxhighlight lang="draco">proc sieve([*] bool prime) void:
word max, p, c;
max := dim(prime,1)-1;
Line 1,294 ⟶ 1,487:
writeln();
writeln("There are ", n, " additive primes below ", MAX)
corp</langsyntaxhighlight>
{{out}}
<pre> 2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151
Line 1,300 ⟶ 1,493:
353 359 373 379 397 401 409 421 443 449 461 463 467 487
There are 54 additive primes below 500</pre>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="easylang">
func prime n .
if n mod 2 = 0 and n > 2
return 0
.
i = 3
sq = sqrt n
while i <= sq
if n mod i = 0
return 0
.
i += 2
.
return 1
.
func digsum n .
while n > 0
sum += n mod 10
n = n div 10
.
return sum
.
for i = 2 to 500
if prime i = 1
s = digsum i
if prime s = 1
write i & " "
.
.
.
print ""
</syntaxhighlight>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
main(_) ->
AddPrimes = [N || N <- lists:seq(2,500), isprime(N) andalso isprime(digitsum(N))],
Line 1,319 ⟶ 1,547:
digitsum(0, S) -> S;
digitsum(N, S) -> digitsum(N div 10, S + N rem 10).
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,332 ⟶ 1,560:
=={{header|F_Sharp|F#}}==
This task uses [http://www.rosettacode.org/wiki/Extensible_prime_generator#The_functions Extensible Prime Generator (F#)]
<langsyntaxhighlight lang="fsharp">
// Additive Primes. Nigel Galloway: March 22nd., 2021
let rec fN g=function n when n<10->n+g |n->fN(g+n%10)(n/10)
primes32()|>Seq.takeWhile((>)500)|>Seq.filter(fN 0>>isPrime)|>Seq.iter(printf "%d "); printfn ""
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,344 ⟶ 1,572:
=={{header|Factor}}==
{{works with|Factor|0.99 2021-02-05}}
<langsyntaxhighlight lang="factor">USING: formatting grouping io kernel math math.primes
prettyprint sequences ;
 
Line 1,352 ⟶ 1,580:
499 primes-upto [ sum-digits prime? ] filter
[ 9 group simple-table. nl ]
[ length "Found %d additive primes < 500.\n" printf ] bi</langsyntaxhighlight>
{{out}}
<pre>
Line 1,366 ⟶ 1,594:
 
=={{header|Fermat}}==
<langsyntaxhighlight lang="fermat">Function Digsum(n) =
digsum := 0;
while n>0 do
Line 1,383 ⟶ 1,611:
fi od;
 
!!('There were ',nadd);</langsyntaxhighlight>
{{out}}<pre>
Additive primes below 500 are
Line 1,444 ⟶ 1,672:
=={{header|Forth}}==
{{works with|Gforth}}
<langsyntaxhighlight lang="forth">: prime? ( n -- ? ) here + c@ 0= ;
: notprime! ( n -- ) here + 1 swap c! ;
 
Line 1,483 ⟶ 1,711:
 
500 print_additive_primes
bye</langsyntaxhighlight>
 
{{out}}
Line 1,499 ⟶ 1,727:
=={{header|FreeBASIC}}==
As with the other special primes tasks, use one of the primality testing algorithms as an include.
<langsyntaxhighlight lang="freebasic">#include "isprime.bas"
 
function digsum( n as uinteger ) as uinteger
Line 1,520 ⟶ 1,748:
end if
end if
next i</langsyntaxhighlight>
{{out}}
<pre style="height:16em">Prime Digit Sum
Line 1,582 ⟶ 1,810:
then go through the list, sum digits and check for prime
 
<langsyntaxhighlight lang="pascal">
Program AdditivePrimes;
Const max_number = 500;
Line 1,644 ⟶ 1,872:
writeln(counter,' additive primes found.');
End.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,658 ⟶ 1,886:
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">vals = toArray[select[primes[2, 500], {|x| isPrime[sum[integerDigits[x]]]}]]
println[formatTable[columnize[vals, 10]]]
println["\n" + length[vals] + " values found."]</langsyntaxhighlight>
{{out}}
<pre>
Line 1,672 ⟶ 1,900:
54 values found.
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
 
local fn IsPrime( n as NSUInteger ) as BOOL
NSUInteger i
BOOL result = YES
if ( n < 2 ) then exit fn = NO
for i = 2 to n + 1
if ( i * i <= n ) and ( n mod i == 0 )
exit fn = NO
end if
next
end fn = result
 
local fn DigSum( n as NSUInteger ) as NSUInteger
NSUInteger s = 0
while ( n > 0 )
s += ( n mod 10 )
n /= 10
wend
end fn = s
 
void local fn AdditivePrimes( n as NSUInteger )
NSUInteger i, s = 0, counter = 0
printf @"Additive Primes:"
for i = 2 to n
if ( fn IsPrime(i) ) and ( fn IsPrime( fn DigSum(i) ) )
s++
printf @"%4ld \b", i : counter++
if counter == 10 then counter = 0 : print
end if
next
printf @"\n\nFound %lu additive primes less than %lu.", s, n
end fn
 
fn AdditivePrimes( 500 )
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Additive Primes:
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
 
Found 54 additive primes less than 500.
</pre>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Additive_primes}}
 
'''Solution'''
 
[[File:Fōrmulæ - Additive primes 01.png]]
 
'''Test case 1.''' Write a program to determine all additive primes less than 500.
 
[[File:Fōrmulæ - Additive primes 02.png]]
 
[[File:Fōrmulæ - Additive primes 03.png]]
 
'''Test case 2.''' Show the number of additive primes.
 
[[File:Fōrmulæ - Additive primes 04.png]]
 
[[File:Fōrmulæ - Additive primes 05.png]]
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,733 ⟶ 2,035:
}
fmt.Printf("\n\n%d additive primes found.\n", count)
}</langsyntaxhighlight>
 
{{out}}
Line 1,749 ⟶ 2,051:
 
=={{header|J}}==
<langsyntaxhighlight Jlang="j"> (#~ 1 p: [:+/@|: 10&#.inv) i.&.(p:inv) 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</langsyntaxhighlight>
=={{header|Java}}==
<langsyntaxhighlight Javalang="java">public class additivePrimes {
 
public static void main(String[] args) {
Line 1,789 ⟶ 2,091:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,800 ⟶ 2,102:
 
'''Preliminaries'''
<langsyntaxhighlight lang="jq">def is_prime:
. as $n
| if ($n < 2) then false
Line 1,832 ⟶ 2,134:
 
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
</syntaxhighlight>
</lang>
'''The task'''
<syntaxhighlight lang="jq">
<lang jq>
# Input: a number n
# Output: an array of additive primes less than n
Line 1,851 ⟶ 2,153:
| ((nwise(10) | map(lpad(4)) | join(" ")),
"\n\(length) additive primes found."))
</langsyntaxhighlight>
{{out}}
<pre>
Line 1,867 ⟶ 2,169:
=={{header|Haskell}}==
Naive solution which doesn't rely on advanced number theoretic libraries.
<langsyntaxhighlight lang="haskell">import Data.List (unfoldr)
 
-- infinite list of primes
Line 1,884 ⟶ 2,186:
-- test for an additive prime
isAdditivePrime n = isPrime n && (isPrime . sum . digits) n
</syntaxhighlight>
</lang>
 
The task
Line 1,903 ⟶ 2,205:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Primes
 
let
Line 1,917 ⟶ 2,219:
println("\n\n$pcount additive primes found.")
end
</langsyntaxhighlight>{{out}}
<pre>
Erdős primes under 500:
Line 1,929 ⟶ 2,231:
=={{header|Kotlin}}==
{{trans|Python}}
<langsyntaxhighlight lang="kotlin">fun isPrime(n: Int): Boolean {
if (n <= 3) return n > 1
if (n % 2 == 0 || n % 3 == 0) return false
Line 1,959 ⟶ 2,261:
}
println("\nFound $additivePrimes additive primes less than 500")
}</langsyntaxhighlight>
{{out}}
<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
Line 1,965 ⟶ 2,267:
 
=={{header|Ksh}}==
<langsyntaxhighlight lang="ksh">#!/bin/ksh
 
# Prime numbers for which the sum of their decimal digits are also primes
Line 2,011 ⟶ 2,313:
_isprime ${digsum} ; (( $? )) && printf "%4d " ${i}
done
print</langsyntaxhighlight>
{{out}}
<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|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def isprime
{def isprime.loop
{lambda {:n :m :i}
{if {> :i :m}
then true
else {if {= {% :n :i} 0}
then false
else {isprime.loop :n :m {+ :i 2}}
}}}}
{lambda {:n}
{if {or {= :n 2} {= :n 3} {= :n 5} {= :n 7}}
then true
else {if {or {< : n 2} {= {% :n 2} 0}}
then false
else {isprime.loop :n {sqrt :n} 3}
}}}}
-> isprime
 
{def digit.sum
{def digit.sum.loop
{lambda {:n :sum}
{if {> :n 0}
then {digit.sum.loop {floor {/ :n 10}}
{+ :sum {% :n 10}}}
else :sum}}}
{lambda {:n}
{digit.sum.loop :n 0}}}
-> digit.sum
 
{S.replace \s by space in
{S.map {lambda {:i}
{if {and {isprime :i}
{isprime {digit.sum :i}}}
then :i
else}}
{S.serie 2 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
i.e 54 additive primes until 500.
</syntaxhighlight>
 
=={{header|langur}}==
<syntaxhighlight lang ="langur">val .isPrime = f fn(.i == 2 or .i > 2 and not any f(.x) .i div .x, pseries 2 to .i ^/ 2{
.i == 2 or .i > 2 and
not any fn(.x) { .i div .x }, pseries 2 .. .i ^/ 2
}
 
val .sumDigits = ffn(.i) { fold ffn{+}, s2n toStringstring .i }
 
writeln "Additive primes less than 500:"
Line 2,027 ⟶ 2,375:
for .i in [2] ~ series(3..500, 2) {
if .isPrime(.i) and .isPrime(.sumDigits(.i)) {
write $"\{.i:3;} "
.count += 1
if .count div 10: writeln()
Line 2,033 ⟶ 2,381:
}
 
writeln $"\n\n\{.count;} additive primes found.\n"
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,047 ⟶ 2,395:
54 additive primes found.
</pre>
 
 
 
=={{header|Lua}}==
This task uses <code>primegen</code> from: [[Extensible_prime_generator#Lua]]
<langsyntaxhighlight lang="lua">function sumdigits(n)
local sum = 0
while n > 0 do
Line 2,064 ⟶ 2,410:
aprimes = primegen:filter(function(n) return primegen.tbd(sumdigits(n)) end)
print(table.concat(aprimes, " "))
print("Count:", #aprimes)</langsyntaxhighlight>
{{out}}
<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
Line 2,070 ⟶ 2,416:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[AdditivePrimeQ]
AdditivePrimeQ[n_Integer] := PrimeQ[n] \[And] PrimeQ[Total[IntegerDigits[n]]]
Select[Range[500], AdditivePrimeQ]</langsyntaxhighlight>
{{out}}
<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|Maxima}}==
<syntaxhighlight lang="maxima">
/* Function that returns a list of digits given a nonnegative integer */
decompose(num) := block([digits, remainder],
digits: [],
while num > 0 do
(remainder: mod(num, 10),
digits: cons(remainder, digits),
num: floor(num/10)),
digits
)$
 
/* Routine that extracts from primes between 2 and 500, inclusive, the additive primes */
block(
primes(2,500),
sublist(%%,lambda([x],primep(apply("+",decompose(x))))));
 
/* Number of additive primes in the rank */
length(%);
</syntaxhighlight>
{{out}}
<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]
 
54
</pre>
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">
isPrime = function(n)
if n <= 3 then return n > 1
if n % 2 == 0 or n % 3 == 0 then return false
i = 5
while i ^ 2 <= n
if n % i == 0 or n % (i + 2) == 0 then return false
i += 6
end while
return true
end function
 
digitSum = function(n)
sum = 0
while n > 0
sum += n % 10
n = floor(n / 10)
end while
return sum
end function
 
additive = []
 
for i in range(2, 500)
if isPrime(i) and isPrime(digitSum(i)) then additive.push(i)
end for
print "There are " + additive.len + " additive primes under 500."
print additive
</syntaxhighlight>
 
{{out}}
<pre>
miniscript.exe additive-prime.ms
There are 54 additive primes under 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]
</pre>
 
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout (table 5 10 nums), Stdout countmsg]
where nums = filter additive_prime [1..500]
countmsg = "Found " ++ show (#nums) ++ " additive primes < 500\n"
 
table :: num->num->[num]->[char]
table w c ls = lay [concat (map (rjustify w . show) l) | l <- split c ls]
 
split :: num->[*]->[[*]]
split n ls = [ls], if #ls < n
= take n ls:split n (drop n ls), otherwise
 
additive_prime :: num->bool
additive_prime n = prime (dsum n) & prime n
 
dsum :: num->num
dsum n = n, if n<10
= n mod 10 + dsum (n div 10), otherwise
 
prime :: num->bool
prime n = n>=2 & #[d | d<-[2..entier (sqrt n)]; n mod d=0] = 0</syntaxhighlight>
{{out}}
<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
Found 54 additive primes < 500</pre>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE AdditivePrimes;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
 
Line 2,130 ⟶ 2,572:
WriteString('.');
WriteLn();
END AdditivePrimes.</langsyntaxhighlight>
{{out}}
<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
There are 54 additive primes less than 500.</pre>
 
=={{header|Modula-3}}==
{{trans|Modula-2}}
<syntaxhighlight lang="modula3">MODULE AdditivePrimes EXPORTS Main;
 
IMPORT SIO,Fmt;
 
CONST
Max = 500;
 
VAR
Count:CARDINAL := 0;
Prime:ARRAY[2..Max] OF BOOLEAN;
 
PROCEDURE DigitSum(N:CARDINAL):CARDINAL =
BEGIN
IF N < 10 THEN RETURN N
ELSE RETURN (N MOD 10) + DigitSum(N DIV 10) END;
END DigitSum;
 
PROCEDURE Sieve() =
VAR J:CARDINAL;
BEGIN
FOR I := 2 TO Max DO Prime[I] := TRUE END;
FOR I := 2 TO Max DIV 2 DO
IF Prime[I] THEN
J := I*2;
WHILE J <= Max DO
Prime[J] := FALSE;
INC(J,I)
END
END
END;
END Sieve;
BEGIN
Sieve();
FOR N := 2 TO Max DO
IF Prime[N] AND Prime[DigitSum(N)] THEN
SIO.PutText(Fmt.F("%4s",Fmt.Int(N)));
INC(Count);
IF Count MOD 10 = 0 THEN SIO.Nl() END
END
END;
SIO.PutText(Fmt.F("\nThere are %s additive primes less than %s.\n",
Fmt.Int(Count),Fmt.Int(Max)));
END AdditivePrimes.
</syntaxhighlight>
 
{{out}}
<pre> 2 3 5 7 11 23 29 41 43 47
Line 2,141 ⟶ 2,640:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import math, strutils
 
const N = 499
Line 2,171 ⟶ 2,670:
echo()
 
echo "\nNumber of additive primes found: ", count</langsyntaxhighlight>
 
{{out}}
Line 2,183 ⟶ 2,682:
 
Number of additive primes found: 54</pre>
 
=={{header|Oberon-07}}==
{{Trans|Modula-3}}
<syntaxhighlight lang="modula2">
MODULE AdditivePrimes;
 
IMPORT
Out;
 
CONST
Max = 500;
 
VAR
Count, n :INTEGER;
Prime :ARRAY Max + 1 OF BOOLEAN;
 
PROCEDURE DigitSum( n :INTEGER ):INTEGER;
VAR result :INTEGER;
BEGIN
result := 0;
IF n < 10 THEN result := n
ELSE result := ( n MOD 10 ) + DigitSum( n DIV 10 )
END
RETURN result
END DigitSum;
 
PROCEDURE Sieve;
VAR i, j :INTEGER;
BEGIN
Prime[ 0 ] := FALSE; Prime[ 1 ] := FALSE;
FOR i := 2 TO Max DO Prime[ i ] := TRUE END;
FOR i := 2 TO Max DIV 2 DO
IF Prime[ i ] THEN
j := i * 2;
WHILE j <= Max DO
Prime[ j ] := FALSE;
j := j + i
END
END
END
END Sieve;
BEGIN
Sieve;
FOR n := 2 TO Max DO
IF Prime[ n ] & Prime[ DigitSum( n ) ] THEN
Out.Int( n, 4 );
Count := Count + 1;
IF Count MOD 20 = 0 THEN Out.Ln END
END
END;
Out.Ln;Out.String( "There are " );Out.Int( Count, 1 );
Out.String( " additive primes less than " );Out.Int( Max, 1 );
Out.String( "." );Out.Ln
END AdditivePrimes.
</syntaxhighlight>
{{out}}
<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
There are 54 additive primes less than 500.
</pre>
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">let rec digit_sum n =
if n < 10 then n else n mod 10 + digit_sum (n / 10)
 
let is_prime n =
let rec test x =
let q = n / x in x > q || x * q <> n && n mod (x + 2) <> 0 && test (x + 6)
in if n < 5 then n lor 1 = 3 else n land 1 <> 0 && n mod 3 <> 0 && test 5
 
let is_additive_prime n =
is_prime n && is_prime (digit_sum n)
 
let () =
Seq.ints 0 |> Seq.take_while ((>) 500) |> Seq.filter is_additive_prime
|> Seq.iter (Printf.printf " %u") |> print_newline</syntaxhighlight>
{{out}}
<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|Pari/GP}}==
This is a good task for demonstrating several different ways to approach a simple problem.
<langsyntaxhighlight lang="parigp">hasPrimeDigitsum(n)=isprime(sumdigits(n)); \\ see A028834 in the OEIS
 
v1 = select(isprime, select(hasPrimeDigitsum, [1..499]));
Line 2,193 ⟶ 2,773:
 
s=0; forprime(p=2,499, if(hasPrimeDigitsum(p), s++)); s;
[#v1, #v2, #v3, s]</langsyntaxhighlight>
{{out}}
<pre>%1 = [54, 54, 54, 54]</pre>
 
=={{header|Pascal}}==
{{works with|Free Pascal}}{{works with|Delphi}} checking isPrime(sum of digits) before testimg isprime(num) improves speed.<br>Tried to speed up calculation of sum of digits.
<langsyntaxhighlight lang="pascal">program AdditivePrimes;
{$IFDEF FPC}
{$MODE DELPHI}{$CODEALIGN proc=16}
Line 2,346 ⟶ 2,927:
writeln(cnt, ' additive primes found.');
END.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,361 ⟶ 2,942:
=={{header|Perl}}==
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use ntheory 'is_prime';
Line 2,375 ⟶ 2,956:
is_prime($_) and is_prime(sum(split '',$_)) and push @ap, $_ for 1..$limit;
 
print @ap . " additive primes < $limit:\n" . pp(@ap);</langsyntaxhighlight>
{{out}}
<pre>54 additive primes < 500:
Line 2,384 ⟶ 2,965:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">additive</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #7060A8;">is_prime</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">)))</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">filter</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">get_primes_le</span><span style="color: #0000FF;">(</span><span style="color: #000000;">500</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">sprint</span><span style="color: #0000FF;">),</span><span style="color: #000000;">additive</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d additive primes found: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">))})</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,396 ⟶ 2,977:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/Additive_primes
by Galileo, 05/2022 #/
 
Line 2,422 ⟶ 3,003:
 
"Additive primes found: " print print
</syntaxhighlight>
</lang>
{{out}}
<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 Additive primes found: 54
Line 2,428 ⟶ 3,009:
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">main =>
PCount = 0,
foreach (I in 2..499)
Line 2,440 ⟶ 3,021:
sum_digits(N) = S =>
S = sum([ord(C)-ord('0') : C in to_string(N)]).
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,450 ⟶ 3,031:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de prime? (N)
(let D 0
(or
Line 2,470 ⟶ 3,051:
(inc 'C) ) )
(prinl)
(prinl "Total count: " C) )</langsyntaxhighlight>
{{out}}
<pre>
Line 2,478 ⟶ 3,059:
 
=={{header|PILOT}}==
<langsyntaxhighlight lang="pilot">C :z=2
:c=0
:max=500
Line 2,520 ⟶ 3,101:
:i=j
J (i>0):*digit
E :</langsyntaxhighlight>
{{out}}
<pre style='height:50ex;'>2
Line 2,590 ⟶ 3,171:
The PL/I include file "pg.inc" can be found on the [[Polyglot:PL/I and PL/M]] page.
Note the use of text in column 81 onwards to hide the PL/I specifics from the PL/M compiler.
<langsyntaxhighlight lang="pli">/* FIND ADDITIVE PRIMES - PRIMES WHOSE DIGIT SUM IS ALSO PRIME */
additive_primes_100H: procedure options (main);
 
Line 2,677 ⟶ 3,258:
CALL PRNL;
 
EOF: end additive_primes_100H;</langsyntaxhighlight>
{{out}}
<pre>
Line 2,689 ⟶ 3,270:
 
=={{header|Processing}}==
<langsyntaxhighlight lang="processing">IntList primes = new IntList();
 
void setup() {
Line 2,724 ⟶ 3,305:
}
}
}</langsyntaxhighlight>
{{out}}
<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
Line 2,730 ⟶ 3,311:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">#MAX=500
Global Dim P.b(#MAX) : FillMemory(@P(),#MAX,1,#PB_Byte)
If OpenConsole()=0 : End 1 : EndIf
Line 2,744 ⟶ 3,325:
Next
PrintN(~"\n\n"+Str(c)+" additive primes below 500.")
Input()</langsyntaxhighlight>
{{out}}
<pre> 2 3 5 7 11 23 29 41 43 47
Line 2,756 ⟶ 3,337:
 
=={{header|Python}}==
<langsyntaxhighlight Pythonlang="python">def is_prime(n: int) -> bool:
if n <= 3:
return n > 1
Line 2,784 ⟶ 3,365:
 
if __name__ == "__main__":
main()</langsyntaxhighlight>
{{out}}
<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
Line 2,795 ⟶ 3,376:
<code>digitsum</code> is defined at [[Sum digits of an integer#Quackery]].
 
<langsyntaxhighlight Quackerylang="quackery"> 500 eratosthenes
[]
Line 2,804 ⟶ 3,385:
[ i^ join ] ] ]
dup echo cr cr
size echo say " additive primes found."</langsyntaxhighlight>
 
{{out}}
Line 2,811 ⟶ 3,392:
 
54 additive primes found.</pre>
 
=={{header|R}}==
<syntaxhighlight lang="R">
digitsum <- function(x) sum(floor(x / 10^(0:(nchar(x) - 1))) %% 10)
 
is.prime <- function(n) n == 2L || all(n %% 2L:max(2,floor(sqrt(n))) != 0)
 
range_int <- 2:500
v <- sapply(range_int, \(x) is.prime(x) && is.prime(digitsum(x)))
 
cat(paste("Found",length(range_int[v]),"additive primes less than 500"))
print(range_int[v])
</syntaxhighlight>
{{out}}
<pre>Found 54 additive primes less than 500
[1] 2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151 157 173 179
[24] 191 193 197 199 223 227 229 241 263 269 281 283 311 313 317 331 337 353 359 373 379 397 401
[47] 409 421 443 449 461 463 467 487</pre>
 
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">#lang racket
 
(require math/number-theory)
Line 2,828 ⟶ 3,427:
(define additive-primes<500 (filter additive-prime? (range 1 500)))
(printf "There are ~a additive primes < 500~%" (length additive-primes<500))
(printf "They are: ~a~%" additive-primes<500)</langsyntaxhighlight>
 
{{out}}
Line 2,836 ⟶ 3,435:
 
=={{header|Raku}}==
<syntaxhighlight lang="raku" perl6line>unit sub MAIN ($limit = 500);
say "{+$_} additive primes < $limit:\n{$_».fmt("%" ~ $limit.chars ~ "d").batch(10).join("\n")}",
with ^$limit .grep: { .is-prime and .comb.sum.is-prime }</langsyntaxhighlight>
{{out}}
<pre>54 additive primes < 500:
Line 2,849 ⟶ 3,448:
 
=={{header|Red}}==
<syntaxhighlight lang="red">
<lang Red>
cross-sum: function [n][out: 0 foreach m form n [out: out + to-integer to-string m]]
additive-primes: function [n][collect [foreach p ps: primes n [if find ps cross-sum p [keep p]]]]
Line 2,863 ⟶ 3,462:
]
== 54
</syntaxhighlight>
</lang>
Uses <code>primes</code> defined in https://rosettacode.org/wiki/Sieve_of_Eratosthenes#Red.
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program counts/displays the number of additive primes underless a specified numberthan N. */
parseParse argArg n cols . /*get optional number of primes toTo find*/
ifIf n=='' | n=="',"' thenThen n= 500 /*Not specified? Then assume default.*/
ifIf cols=='' | cols=="',"' thenThen cols= 10 /* "' "' "' "' "' */
call genP n /*generate all primes under N. */
w= 10 5 /*width of a number in any column. */
title= " 'additive primes that are < " 'commas(n)
ifIf cols>0 thenThen saySay ' index ¦'center(title, 1 + cols*(w+1) +1)
ifIf cols>0 thenThen saySay '───────┼-------+'center(""'' , 1 + cols*(w+1)+1, '-')
found=0
found= 0; idx= 1 /*initialize # of additive primes & IDX*/
$ol= '' /*a list of additive primes (so far). */
idx=1
do j=1 for #; p= @.j /*obtain the Jth prime. */
Do j=1 By 1
_= sumDigs(p); if \!._ then iterate /*is sum of J's digs a prime? No, skip.*/ /* ◄■■■■■■■■ a filter. */
p=p.j found= found + 1 /*bumpobtain the count ofJth additive primesprime. */
If p>n Then Leave if cols<0 then iterate /*Build theno more needed list (to be shown later)? */
_=sumDigs(p)
c= commas(p) /*maybe add commas to the number. */
If !._ Then Do
$= $ right(c, max(w, length(c) ) ) /*add additive prime──►list, allow big#*/
found=found+1 if found//cols\==0 then iterate /*havebump wethe populatedcount aof lineadditive ofprimes. output? */
c=commas(p) say center(idx, 7)'│' substr($, 2); $= /*displaymaybe whatadd wecommas To the number. have so far (cols). */
ol=ol right(c,max(w,length(c))) /*add additive prime--?list,allow big# */
idx= idx + cols /*bump the index count for the output*/
If words(ol)=10 Then Do /* a line is complete */
end /*j*/
Say center(idx,7)'¦' substr(ol,2) /*display what we have so far (cols). */
ol='' /* prepare for next line */
idx=idx+10
End
End
End /*j*/
 
If ol\=='' Then
if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible display residual output.*/
Say center(idx,7)'¦' substr(ol,2) /*possible display residual output. */
if cols>0 then say '───────┴'center("" , 1 + cols*(w+1), '─')
If cols>0 Then
say
Say '--------'center('',cols*(w+1)+1,'-')
say 'found ' commas(found) title
Say
exit 0 /*stick a fork in it, we're all done. */
Say 'found ' commas(found) title
/*──────────────────────────────────────────────────────────────────────────────────────*/
Exit 0 /*stick a fork in it, we're all done. */
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?
/*--------------------------------------------------------------------------------*/
sumDigs: parse arg x 1 s 2; do k=2 for length(x)-1; s= s + substr(x,k,1); end; return s
commas: Parse Arg ?; Do jc=length(?)-3 To 1 by -3; ?=insert(',',?,jc); End; Return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
sumDigs:Parse Arg x 1 s 2; Do k=2 For length(x)-1; s=s+substr(x,k,1); End; Return s
genP: parse arg n; @.1= 2; @.2= 3; @.3= 5; @.4= 7; @.5= 11; @.6= 13
/*--------------------------------------------------------------------------------*/
!.= 0; !.2= 1; !.3= 1; !.5= 1; !.7= 1; !.11= 1; !.13= 1
genP:
#= 6; sq.#= @.# ** 2 /*the number of primes; prime squared.*/
Parse Arg n
do j=@.#+2 by 2 for max(0, n%2-@.#%2-1) /*find odd primes from here on. */
pl=2 3 5 7 11 13
parse var j '' -1 _ /*obtain the last digit of the J var.*/
!.=0
if _==5 then iterate; if j// 3==0 then iterate /*J ÷ by 5? J ÷ by 3? */
Do np=1 By 1 While pl<>''
if j// 7==0 then iterate; if j//11==0 then iterate /*" " " 7? " " " 11? */
Parse Var pl p pl
/* [↓] divide by the primes. ___ */
p.np=p
do k=6 while sq.k<=j /*divide J by other primes ≤ √ J */
sq.np=p*p
if j//@.k==0 then iterate j /*÷ by prev. prime? ¬prime ___ */
!.p=1
end /*k*/ /* [↑] only divide up to √ J */
End
#= # + 1; @.#= j; sq.#= j*j; !.j= 1 /*bump prime count; assign prime & flag*/
np=np-1
end /*j*/; return</lang>
Do j=p.np+2 by 2 While j<n
Parse Var j '' -1 _ /*obtain the last digit of the J var.*/
If _==5 Then Iterate
If j// 3==0 Then Iterate
If j// 7==0 Then Iterate
If j//11==0 Then Iterate
Do k=6 By 1 While sq.k<=j /*divide J by other primes <=sqrt(j) */
If j//p.k==0 Then Iterate j /* not prime - try next */
End /*k*/
np=np+1 /*bump prime count; assign prime & flag*/
p.np=j
sq.np=j*j
!.j=1
End /*j*/
Return</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
index ¦ additive primes that are < 500
-------+-------------------------------------------------------------
───────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────
1 ¦ 2 3 5 7 11 23 29 41 43 47
11 ¦ 61 67 83 89 101 113 131 137 139 151
21 ¦ 157 173 179 191 193 197 199 223 227 229
31 ¦ 241 263 269 281 283 311 313 317 331 337
41 ¦ 353 359 373 379 397 401 409 421 443 449
51 ¦ 461 463 467 487
---------------------------------------------------------------------
───────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────
 
found 54 additive primes that are < 500
</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
 
Line 2,955 ⟶ 3,575:
see nl + "found " + row + " additive primes." + nl
see "done..." + nl
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,969 ⟶ 3,589:
done...
</pre>
=={{header|RPL}}==
{{works with|HP|49g}}
≪ →STR 0
1 3 PICK SIZE '''FOR''' j
OVER j DUP SUB STR→ + '''NEXT''' NIP
≫ '<span style="color:blue>∑DIGITS</span>' STO
≪ { } 1
'''DO'''
NEXTPRIME
'''IF''' DUP <span style="color:blue>∑DIGITS</span> ISPRIME? '''THEN''' SWAP OVER + SWAP '''END'''
'''UNTIL''' DUP 500 ≥ '''END'''
DROP DUP SIZE
≫ '<span style="color:blue>TASK</span>' STO
{{out}}
<pre>
2: { 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 }
1: 54
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require "prime"
 
additive_primes = Prime.lazy.select{|prime| prime.digits.sum.prime? }
Line 2,978 ⟶ 3,618:
puts res.join(" ")
puts "\n#{res.size} additive primes below #{N}."
</syntaxhighlight>
</lang>
{{out}}
<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
Line 2,984 ⟶ 3,624:
54 additive primes below 500.
</pre>
 
 
=={{header|Rust}}==
 
===Flat implementation===
<langsyntaxhighlight fsharplang="rust">fn main() {
let limit = 500;
let column_w = limit.to_string().len() + 1;
Line 3,005 ⟶ 3,644:
}
println!("\n---\nFound {count} additive primes less than {limit}");
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,021 ⟶ 3,660:
primal implements the sieve of Eratosthenes with optimizations (10+ times faster for large limits)
 
<langsyntaxhighlight fsharplang="rust">// [dependencies]
// primal = "0.3.0"
 
Line 3,039 ⟶ 3,678:
.count();
println!("\n---\nFound {count} additive primes less than {limit}");
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,054 ⟶ 3,693:
 
=={{header|Sage}}==
<syntaxhighlight lang="sagemath">
<lang SageMath>
limit = 500
additivePrimes = list(filter(lambda x: x > 0,
Line 3,060 ⟶ 3,699:
list(map(str,list(primes(1,limit))))))))
print(f"{additivePrimes}\nFound {len(additivePrimes)} additive primes less than {limit}")
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,067 ⟶ 3,706:
</pre>
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func boolean: isPrime (in integer: number) is func
Line 3,112 ⟶ 3,751:
end for;
writeln("\nFound " <& count <& " additive primes < 500.");
end func;</langsyntaxhighlight>
{{out}}
<pre>
Line 3,124 ⟶ 3,763:
Found 54 additive primes < 500.
</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program additive_primes;
loop for i in [i : i in [1..499] | additive_prime i] do
nprint(lpad(str i, 4));
if (n +:= 1) mod 10 = 0 then
print;
end if;
end loop;
print;
print("There are " + str n + " additive primes less than 500.");
 
op additive_prime(n);
return prime n and prime digitsum n;
end op;
 
op prime(n);
return n>=2 and not exists d in {2..floor sqrt n} | n mod d = 0;
end op;
 
op digitsum(n);
loop while n>0;
s +:= n mod 10;
n div:= 10;
end loop;
return s;
end op;
end program;
</syntaxhighlight>
 
{{out}}
<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
There are 54 additive primes less than 500.</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func additive_primes(upto, base = 10) {
upto.primes.grep { .sumdigits(base).is_prime }
}
Line 3,132 ⟶ 3,809:
additive_primes(500).each_slice(10, {|*a|
a.map { '%3s' % _ }.join(' ').say
})</langsyntaxhighlight>
{{out}}
<pre>
Line 3,144 ⟶ 3,821:
 
=={{header|TSE SAL}}==
<syntaxhighlight lang="tsesal">
<lang TSESAL>
 
INTEGER PROC FNMathGetSquareRootI( INTEGER xI )
Line 3,254 ⟶ 3,931:
END
 
</syntaxhighlight>
</lang>
 
{{out}} <pre>
Line 3,316 ⟶ 3,993:
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">import Foundation
 
func isPrime(_ n: Int) -> Bool {
Line 3,361 ⟶ 4,038:
}
}
print("\n\(count) additive primes found.")</langsyntaxhighlight>
 
{{out}}
Line 3,375 ⟶ 4,052:
</pre>
 
=={{header|VlanguBasic/4tH}}==
{{trans|BASIC256}}
<syntaxhighlight lang="text">print "Prime", "Digit Sum"
for i = 2 to 499
if func(_isPrime(i)) then
s = func(_digSum(i))
if func(_isPrime(s)) then
print i, s
endif
endif
next
end
 
_isPrime
param (1)
local (1)
 
if a@ < 2 then return (0)
if a@ % 2 = 0 then return (a@ = 2)
if a@ % 3 = 0 then return (a@ = 3)
b@ = 5
do while (b@ * b@) < (a@ + 1)
if a@ % b@ = 0 then unloop : return (0)
b@ = b@ + 2
loop
return (1)
_digSum
param (1)
local (1)
 
b@ = 0
do while a@
b@ = b@ + (a@ % 10)
a@ = a@ / 10
loop
return (b@)</syntaxhighlight>
{{Out}}
<pre>Prime Digit Sum
2 2
3 3
5 5
7 7
11 2
23 5
29 11
41 5
43 7
47 11
61 7
67 13
83 11
89 17
101 2
113 5
131 5
137 11
139 13
151 7
157 13
173 11
179 17
191 11
193 13
197 17
199 19
223 7
227 11
229 13
241 7
263 11
269 17
281 11
283 13
311 5
313 7
317 11
331 7
337 13
353 11
359 17
373 13
379 19
397 19
401 5
409 13
421 7
443 11
449 17
461 11
463 13
467 17
487 19
 
0 OK, 0:176</pre>
 
=={{header|Uiua}}==
{{works with|Uiua|0.10.0-dev.1}}
<syntaxhighlight lang="Uiua">
[] # list of primes to be populated
↘2⇡500 # candidates (starting at 2)
 
# Take the first remaining candidate, which will be prime, save it,
# then remove every candidate that it divides. Repeat until none left.
⍢(▽≠0◿⊃⊢(.↘1)⟜(⊂⊢)|>0⧻)
# Tidy up.
⇌◌
 
# Build sum of digits of each.
≡(/+≡⋕°⋕)...
# Mask out those that result in non-primes.
⊏⊚±⬚0⊏⊗
# Return values and length.
⧻.
</syntaxhighlight>
{{out}}
<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]
54
</pre>
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">fn is_prime(n int) bool {
if n < 2 {
return false
Line 3,432 ⟶ 4,229:
}
println("\n\n$count additive primes found.")
}</langsyntaxhighlight>
 
{{out}}
Line 3,448 ⟶ 4,245:
 
=={{header|VTL-2}}==
<langsyntaxhighlight VTL2lang="vtl2">10 M=499
20 :1)=1
30 P=2
Line 3,481 ⟶ 4,278:
330 ?=N
340 ?=" additive primes below ";
350 ?=M+1</langsyntaxhighlight>
{{out}}
<pre>2 3 5 7 11 23 29 41 43 47
Line 3,494 ⟶ 4,291:
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./math" for Int
import "./fmt" for Fmt
 
var sumDigits = Fn.new { |n|
Line 3,516 ⟶ 4,313:
}
}
System.print("\n\n%(count) additive primes found.")</langsyntaxhighlight>
 
{{out}}
Line 3,532 ⟶ 4,329:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">func IsPrime(N); \Return 'true' if N is a prime number
int N, I;
[if N <= 1 then return false;
Line 3,561 ⟶ 4,358:
Text(0, " additive primes found below 500.
");
]</langsyntaxhighlight>
 
{{out}}
Line 3,575 ⟶ 4,372:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Additive_primes
// by Galileo, 06/2022
 
Line 3,602 ⟶ 4,399:
next
 
print "\nFound: ", count</langsyntaxhighlight>
{{out}}
<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
3,021

edits