Additive primes: Difference between revisions
m
→{{header|ALGOL 68}}: Avoid line wrap
m (BASIC256 moved to the BASIC section.) |
m (→{{header|ALGOL 68}}: Avoid line wrap) |
||
(26 intermediate revisions by 15 users not shown) | |||
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}}
Line 398 ⟶ 428:
FI
OD;
print( ( newline, "Found ", whole( additive count, 0 )
print( ( " additive primes below ", whole( UPB prime + 1, 0 ), newline ) )
END</syntaxhighlight>
{{out}}
Line 1,327 ⟶ 1,358:
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>
=={{header|Delphi}}==
Line 1,377 ⟶ 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}}==
Line 1,749 ⟶ 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}}==
Line 2,137 ⟶ 2,362:
=={{header|langur}}==
<syntaxhighlight lang="langur">val .isPrime = fn(.i) {
.i == 2 or .i > 2 and
not any fn(.x) { .i div .x }, pseries 2 .. .i ^/ 2
}
val .sumDigits =
writeln "Additive primes less than 500:"
Line 2,148 ⟶ 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,154 ⟶ 2,381:
}
writeln $"\n\n\{.count
</syntaxhighlight>
Line 2,194 ⟶ 2,421:
{{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}}==
Line 2,250 ⟶ 2,573:
WriteLn();
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|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,302 ⟶ 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}}==
Line 2,949 ⟶ 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>
Line 3,005 ⟶ 3,466:
=={{header|REXX}}==
<syntaxhighlight lang="rexx">/*REXX program counts/displays the number of additive primes
call genP n
w=
found=0
idx=1
Do j=1 By 1
p=p.j
If p>n Then Leave
_=sumDigs(p)
If !._ Then Do
found=found+1
c=commas(p)
ol=ol right(c,max(w,length(c))) /*add additive prime--?list,allow big# */
If words(ol)=10 Then Do /* a line is complete */
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
Say center(idx,7)'¦' substr(ol,2) /*possible display residual output. */
If cols>0 Then
Say '--------'center('',cols*(w+1)+1,'-')
Say
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
/*--------------------------------------------------------------------------------*/
genP:
Parse Arg n
pl=2 3 5 7 11 13
!.=0
Do np=1 By 1 While pl<>''
Parse Var pl p pl
p.np=p
sq.np=p*p
!.p=1
End
np=np-1
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= when using the default inputs:}}
<pre>
index
-------+-------------------------------------------------------------
1
11
21
31
41
51
---------------------------------------------------------------------
found 54
</pre>
Line 3,107 ⟶ 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}}==
<syntaxhighlight lang="ruby">require "prime"
Line 3,122 ⟶ 3,624:
54 additive primes below 500.
</pre>
=={{header|Rust}}==
Line 3,262 ⟶ 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}}==
Line 3,608 ⟶ 4,147:
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}}
Line 3,727 ⟶ 4,291:
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="
import "./fmt" for Fmt
var sumDigits = Fn.new { |n|
|