Additive primes: Difference between revisions

m
→‎{{header|ALGOL 68}}: Avoid line wrap
m (syntax highlighting fixup automation)
m (→‎{{header|ALGOL 68}}: Avoid line wrap)
(37 intermediate revisions by 22 users not shown)
Line 21:
{{trans|Python}}
 
<syntaxhighlight lang="11l">F is_prime(a)
I a == 2
R 1B
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"aarch64 Assemblyassembly">
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program additivePrime64.s */
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}}==
<syntaxhighlight lang=Ada"ada">with Ada.Text_Io;
 
procedure Additive_Primes is
Line 330 ⟶ 406:
=={{header|ALGOL 68}}==
{{libheader|ALGOL 68-primes}}
<syntaxhighlight 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</syntaxhighlight>
{{out}}
Line 363 ⟶ 440:
 
=={{header|ALGOL W}}==
<syntaxhighlight 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 413 ⟶ 490:
=={{header|APL}}==
 
<syntaxhighlight lang=APL"apl">((+⌿(4/10)⊤P)∊P)/P←(~P∊P∘.×P)/P←1↓⍳500</syntaxhighlight>
 
{{out}}
Line 421 ⟶ 498:
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">on sieveOfEratosthenes(limit)
script o
property numberList : {missing value}
Line 469 ⟶ 546:
 
{{output}}
<syntaxhighlight 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}</syntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang=ARM"arm Assemblyassembly">
/* ARM assembly Raspberry PI */
/* program additivePrime.s */
Line 678 ⟶ 755:
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">additives: select 2..500 'x -> and? prime? x prime? sum digits x
 
loop split.every:10 additives 'a ->
Line 697 ⟶ 774:
 
=={{header|AWK}}==
<syntaxhighlight lang=AWK"awk">
# syntax: GAWK -f ADDITIVE_PRIMES.AWK
BEGIN {
Line 740 ⟶ 817:
 
=={{header|BASIC}}==
<syntaxhighlight 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 765 ⟶ 842:
54 additive primes found below 500</pre>
==={{header|Applesoft BASIC}}===
<syntaxhighlight 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 777 ⟶ 854:
</pre>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="freebasic">print "Prime", "Digit Sum"
for i = 2 to 499
if isprime(i) then
Line 808 ⟶ 885:
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
manifest $( limit = 500 $)
 
Line 854 ⟶ 931:
 
=={{header|C}}==
<syntaxhighlight lang=C"c">
#include <stdbool.h>
#include <stdio.h>
Line 942 ⟶ 1,019:
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
 
Line 999 ⟶ 1,076:
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">% Sieve of Erastothenes
% Returns an array [1..max] marking the primes
sieve = proc (max: int) returns (array[bool])
Line 1,052 ⟶ 1,129:
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. ADDITIVE-PRIMES.
Line 1,136 ⟶ 1,213:
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">
(defun sum-of-digits (n)
"Return the sum of the digits of a number"
Line 1,165 ⟶ 1,242:
 
=={{header|Crystal}}==
<syntaxhighlight lang="ruby"># Fast/simple way to generate primes for small values.
# Uses P3 Prime Generator (PG) and its Prime Generator Sequence (PGS).
 
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}}==
<syntaxhighlight lang="draco">proc sieve([*] bool prime) void:
word max, p, c;
max := dim(prime,1)-1;
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"erlang">
main(_) ->
AddPrimes = [N || N <- lists:seq(2,500), isprime(N) andalso isprime(digitsum(N))],
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#)]
<syntaxhighlight 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)
Line 1,344 ⟶ 1,572:
=={{header|Factor}}==
{{works with|Factor|0.99 2021-02-05}}
<syntaxhighlight lang="factor">USING: formatting grouping io kernel math math.primes
prettyprint sequences ;
 
Line 1,366 ⟶ 1,594:
 
=={{header|Fermat}}==
<syntaxhighlight lang="fermat">Function Digsum(n) =
digsum := 0;
while n>0 do
Line 1,444 ⟶ 1,672:
=={{header|Forth}}==
{{works with|Gforth}}
<syntaxhighlight lang="forth">: prime? ( n -- ? ) here + c@ 0= ;
: notprime! ( n -- ) here + 1 swap c! ;
 
Line 1,499 ⟶ 1,727:
=={{header|FreeBASIC}}==
As with the other special primes tasks, use one of the primality testing algorithms as an include.
<syntaxhighlight lang="freebasic">#include "isprime.bas"
 
function digsum( n as uinteger ) as uinteger
Line 1,582 ⟶ 1,810:
then go through the list, sum digits and check for prime
 
<syntaxhighlight lang="pascal">
Program AdditivePrimes;
Const max_number = 500;
Line 1,658 ⟶ 1,886:
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">vals = toArray[select[primes[2, 500], {|x| isPrime[sum[integerDigits[x]]]}]]
println[formatTable[columnize[vals, 10]]]
println["\n" + length[vals] + " values found."]</syntaxhighlight>
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}}==
<syntaxhighlight lang="go">package main
 
import "fmt"
Line 1,749 ⟶ 2,051:
 
=={{header|J}}==
<syntaxhighlight lang=J"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</syntaxhighlight>
=={{header|Java}}==
<syntaxhighlight lang=Java"java">public class additivePrimes {
 
public static void main(String[] args) {
Line 1,800 ⟶ 2,102:
 
'''Preliminaries'''
<syntaxhighlight lang="jq">def is_prime:
. as $n
| if ($n < 2) then false
Line 1,834 ⟶ 2,136:
</syntaxhighlight>
'''The task'''
<syntaxhighlight lang="jq">
# Input: a number n
# Output: an array of additive primes less than n
Line 1,867 ⟶ 2,169:
=={{header|Haskell}}==
Naive solution which doesn't rely on advanced number theoretic libraries.
<syntaxhighlight lang="haskell">import Data.List (unfoldr)
 
-- infinite list of primes
Line 1,903 ⟶ 2,205:
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">using Primes
 
let
Line 1,929 ⟶ 2,231:
=={{header|Kotlin}}==
{{trans|Python}}
<syntaxhighlight lang="kotlin">fun isPrime(n: Int): Boolean {
if (n <= 3) return n > 1
if (n % 2 == 0 || n % 3 == 0) return false
Line 1,965 ⟶ 2,267:
 
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">#!/bin/ksh
 
# Prime numbers for which the sum of their decimal digits are also primes
Line 2,015 ⟶ 2,317:
<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 = fn(.i) {
{{works with|langur|0.10}}
.i == 2 or .i > 2 and
<syntaxhighlight lang=langur>val .isPrime = f .i == 2 or .i > 2 and not any f(.x) .i div .x, pseries 2 to .i ^/ 2
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,028 ⟶ 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,034 ⟶ 2,381:
}
 
writeln $"\n\n\{.count;} additive primes found.\n"
</syntaxhighlight>
 
Line 2,051 ⟶ 2,398:
=={{header|Lua}}==
This task uses <code>primegen</code> from: [[Extensible_prime_generator#Lua]]
<syntaxhighlight lang="lua">function sumdigits(n)
local sum = 0
while n > 0 do
Line 2,069 ⟶ 2,416:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica"mathematica">ClearAll[AdditivePrimeQ]
AdditivePrimeQ[n_Integer] := PrimeQ[n] \[And] PrimeQ[Total[IntegerDigits[n]]]
Select[Range[500], AdditivePrimeQ]</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|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}}==
<syntaxhighlight lang="modula2">MODULE AdditivePrimes;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
 
Line 2,130 ⟶ 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,140 ⟶ 2,640:
 
=={{header|Nim}}==
<syntaxhighlight lang=Nim"nim">import math, strutils
 
const N = 499
Line 2,182 ⟶ 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.
<syntaxhighlight lang="parigp">hasPrimeDigitsum(n)=isprime(sumdigits(n)); \\ see A028834 in the OEIS
 
v1 = select(isprime, select(hasPrimeDigitsum, [1..499]));
Line 2,195 ⟶ 2,776:
{{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.
<syntaxhighlight lang="pascal">program AdditivePrimes;
{$IFDEF FPC}
{$MODE DELPHI}{$CODEALIGN proc=16}
Line 2,360 ⟶ 2,942:
=={{header|Perl}}==
{{libheader|ntheory}}
<syntaxhighlight lang="perl">use strict;
use warnings;
use ntheory 'is_prime';
Line 2,383 ⟶ 2,965:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang=Phix"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>
Line 2,395 ⟶ 2,977:
 
=={{header|Phixmonti}}==
<syntaxhighlight lang=Phixmonti"phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/Additive_primes
by Galileo, 05/2022 #/
 
Line 2,427 ⟶ 3,009:
 
=={{header|Picat}}==
<syntaxhighlight lang=Picat"picat">main =>
PCount = 0,
foreach (I in 2..499)
Line 2,449 ⟶ 3,031:
 
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp"picolisp">(de prime? (N)
(let D 0
(or
Line 2,477 ⟶ 3,059:
 
=={{header|PILOT}}==
<syntaxhighlight lang="pilot">C :z=2
:c=0
:max=500
Line 2,589 ⟶ 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.
<syntaxhighlight lang="pli">/* FIND ADDITIVE PRIMES - PRIMES WHOSE DIGIT SUM IS ALSO PRIME */
additive_primes_100H: procedure options (main);
 
Line 2,688 ⟶ 3,270:
 
=={{header|Processing}}==
<syntaxhighlight lang="processing">IntList primes = new IntList();
 
void setup() {
Line 2,729 ⟶ 3,311:
 
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic"purebasic">#MAX=500
Global Dim P.b(#MAX) : FillMemory(@P(),#MAX,1,#PB_Byte)
If OpenConsole()=0 : End 1 : EndIf
Line 2,755 ⟶ 3,337:
 
=={{header|Python}}==
<syntaxhighlight lang=Python"python">def is_prime(n: int) -> bool:
if n <= 3:
return n > 1
Line 2,794 ⟶ 3,376:
<code>digitsum</code> is defined at [[Sum digits of an integer#Quackery]].
 
<syntaxhighlight lang=Quackery"quackery"> 500 eratosthenes
[]
Line 2,810 ⟶ 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}}==
 
<syntaxhighlight lang="racket">#lang racket
 
(require math/number-theory)
Line 2,835 ⟶ 3,435:
 
=={{header|Raku}}==
<syntaxhighlight lang=perl6"raku" line>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 }</syntaxhighlight>
Line 2,848 ⟶ 3,448:
 
=={{header|Red}}==
<syntaxhighlight lang=Red"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,866 ⟶ 3,466:
 
=={{header|REXX}}==
<syntaxhighlight 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</syntaxhighlight>
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}}==
<syntaxhighlight lang="ring">
load "stdlib.ring"
 
Line 2,968 ⟶ 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"
 
additive_primes = Prime.lazy.select{|prime| prime.digits.sum.prime? }
Line 2,983 ⟶ 3,624:
54 additive primes below 500.
</pre>
 
 
=={{header|Rust}}==
 
===Flat implementation===
<syntaxhighlight lang=fsharp"rust">fn main() {
let limit = 500;
let column_w = limit.to_string().len() + 1;
Line 3,020 ⟶ 3,660:
primal implements the sieve of Eratosthenes with optimizations (10+ times faster for large limits)
 
<syntaxhighlight lang=fsharp"rust">// [dependencies]
// primal = "0.3.0"
 
Line 3,053 ⟶ 3,693:
 
=={{header|Sage}}==
<syntaxhighlight lang=SageMath"sagemath">
limit = 500
additivePrimes = list(filter(lambda x: x > 0,
Line 3,066 ⟶ 3,706:
</pre>
=={{header|Seed7}}==
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func boolean: isPrime (in integer: number) is func
Line 3,123 ⟶ 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}}==
<syntaxhighlight lang="ruby">func additive_primes(upto, base = 10) {
upto.primes.grep { .sumdigits(base).is_prime }
}
Line 3,143 ⟶ 3,821:
 
=={{header|TSE SAL}}==
<syntaxhighlight lang=TSESAL"tsesal">
 
INTEGER PROC FNMathGetSquareRootI( INTEGER xI )
Line 3,315 ⟶ 3,993:
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">import Foundation
 
func isPrime(_ n: Int) -> Bool {
Line 3,376 ⟶ 4,054:
=={{header|uBasic/4tH}}==
{{trans|BASIC256}}
<syntaxhighlight lang="text">print "Prime", "Digit Sum"
for i = 2 to 499
if func(_isPrime(i)) then
Line 3,469 ⟶ 4,147:
 
0 OK, 0:176</pre>
 
=={{header|Vlang}}==
=={{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,542 ⟶ 4,245:
 
=={{header|VTL-2}}==
<syntaxhighlight lang=VTL2"vtl2">10 M=499
20 :1)=1
30 P=2
Line 3,588 ⟶ 4,291:
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang=ecmascript"wren">import "./math" for Int
import "./fmt" for Fmt
 
var sumDigits = Fn.new { |n|
Line 3,626 ⟶ 4,329:
 
=={{header|XPL0}}==
<syntaxhighlight lang=XPL0"xpl0">func IsPrime(N); \Return 'true' if N is a prime number
int N, I;
[if N <= 1 then return false;
Line 3,669 ⟶ 4,372:
 
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic"yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Additive_primes
// by Galileo, 06/2022
 
3,022

edits