
In mathematics,additive primes are prime numbers for which the sum of their decimal digits are also primes.
Write a program to determine (and show here) alladditive primes less than500.
Optionally, show thenumber of additive primes.
F is_prime(a) I a == 2 R 1B I a < 2 | a % 2 == 0 R 0B L(i) (3 .. Int(sqrt(a))).step(2) I a % i == 0 R 0B R 1BF digit_sum(=n) V sum = 0 L n > 0 sum += n % 10 n I/= 10 R sumV additive_primes = 0L(i) 2..499 I is_prime(i) & is_prime(digit_sum(i)) additive_primes++ print(i, end' ‘ ’)print("\nFound "additive_primes‘ additive primes less than 500’)2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151 157 173 179 191 193 197 199 223 227 229 241 263 269 281 283 311 313 317 331 337 353 359 373 379 397 401 409 421 443 449 461 463 467 487 Found 54 additive primes less than 500
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits *//* program additivePrime64.s */ /*******************************************//* Constantes file *//*******************************************//* for this file see task include a file in language AArch64 assembly*/.include "../includeConstantesARM64.inc" .equ MAXI, 500 /*********************************//* Initialized data *//*********************************/.dataszMessResult: .asciz "Prime : @ \n"szMessCounter: .asciz "Number found : @ \n" szCarriageReturn: .asciz "\n" /*********************************//* UnInitialized data *//*********************************/.bss sZoneConv: .skip 24TablePrime: .skip 8 * MAXI /*********************************//* code section *//*********************************/.text.global main main: // entry of program bl createArrayPrime mov x5,x0 // prime number ldr x4,qAdrTablePrime // address prime table mov x10,#0 // init counter mov x6,#0 // indice1: ldr x2,[x4,x6,lsl #3] // load prime mov x9,x2 // save prime mov x7,#0 // init digit sum mov x1,#10 // divisor2: // begin loop mov x0,x2 // dividende udiv x2,x0,x1 msub x3,x2,x1,x0 // compute remainder add x7,x7,x3 // add digit to digit sum cmp x2,#0 // quotient null ? bne 2b // no -> comppute other digit mov x8,#1 // indice4: // prime search loop cmp x8,x5 // maxi ? bge 5f // yes ldr x0,[x4,x8,lsl #3] // load prime cmp x0,x7 // prime >= digit sum ? add x0,x8,1 csel x8,x0,x8,lt // no -> increment indice blt 4b // and loop bne 5f // > mov x0,x9 // equal bl displayPrime add x10,x10,#1 // increment counter5: add x6,x6,#1 // increment first indice cmp x6,x5 // maxi ? blt 1b // and loop mov x0,x10 // number counter ldr x1,qAdrsZoneConv bl conversion10 // call décimal conversion ldr x0,qAdrszMessCounter ldr x1,qAdrsZoneConv // insert conversion in message bl strInsertAtCharInc bl affichageMess // display message 100: // standard end of the program mov x0, #0 // return code mov x8, #EXIT // request to exit program svc #0 // perform the system callqAdrszCarriageReturn: .quad szCarriageReturnqAdrszMessResult: .quad szMessResultqAdrszMessCounter: .quad szMessCounterqAdrTablePrime: .quad TablePrime/******************************************************************//* créate prime array */ /******************************************************************/createArrayPrime: stp x1,lr,[sp,-16]! // save registres ldr x4,qAdrTablePrime // address prime table mov x0,#1 str x0,[x4] // store 1 in array mov x0,#2 str x0,[x4,#8] // store 2 in array mov x0,#3 str x0,[x4,#16] // store 3 in array mov x5,#3 // prine counter mov x7,#5 // first number to test1: mov x6,#1 // indice2: mov x0,x7 // dividende ldr x1,[x4,x6,lsl #3] // load divisor udiv x2,x0,x1 msub x3,x2,x1,x0 // compute remainder cmp x3,#0 // null remainder ? beq 4f // yes -> end loop cmp x2,x1 // quotient < divisor bge 3f str x7,[x4,x5,lsl #3] // dividende is prime store in array add x5,x5,#1 // increment counter b 4f // and end loop3: add x6,x6,#1 // else increment indice cmp x6,x5 // maxi ? blt 2b // no -> loop4: add x7,x7,#2 // other odd number cmp x7,#MAXI // maxi ? blt 1b // no -> loop mov x0,x5 // return counter100: ldp x1,lr,[sp],16 // restaur des 2 registres ret/******************************************************************//* Display prime table elements */ /******************************************************************//* x0 contains the prime */displayPrime: stp x1,lr,[sp,-16]! // save registres ldr x1,qAdrsZoneConv bl conversion10 // call décimal conversion ldr x0,qAdrszMessResult ldr x1,qAdrsZoneConv // insert conversion in message bl strInsertAtCharInc bl affichageMess // display message100: ldp x1,lr,[sp],16 // restaur des 2 registres retqAdrsZoneConv: .quad sZoneConv /********************************************************//* File Include fonctions *//********************************************************//* for this file see task include a file in language AArch64 assembly */.include "../includeARM64.inc"
Prime : 2Prime : 3Prime : 5Prime : 7Prime : 11Prime : 23Prime : 29Prime : 41Prime : 43Prime : 47Prime : 61Prime : 67Prime : 83Prime : 89Prime : 101Prime : 113Prime : 131Prime : 137Prime : 139Prime : 151Prime : 157Prime : 173Prime : 179Prime : 191Prime : 193Prime : 197Prime : 199Prime : 223Prime : 227Prime : 229Prime : 241Prime : 263Prime : 269Prime : 281Prime : 283Prime : 311Prime : 313Prime : 317Prime : 331Prime : 337Prime : 353Prime : 359Prime : 373Prime : 379Prime : 397Prime : 401Prime : 409Prime : 421Prime : 443Prime : 449Prime : 461Prime : 463Prime : 467Prime : 487Number found : 54
HOW TO REPORT prime n: REPORT n>=2 AND NO d IN {2..floor root n} HAS n mod d = 0HOW 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 nPUT 0 IN nFOR 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."/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 487There are 54 additive primes less than 500.
;;; find some additive primes - primes whose digit sum is also prime;;; Library: Action! Sieve of EratosthenesINCLUDE "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()RETURN2 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 487Found 54 additive primes below 501
withAda.Text_Io;procedureAdditive_PrimesisLast:constant:=499;Columns:constant:=12;typePrime_Listisarray(2..Last)ofBoolean;functionGet_PrimesreturnPrime_ListisPrime:Prime_List:=(others=>True);beginforPinPrime'RangeloopifPrime(P)thenforNin2..Positive'LastloopexitwhenN*PnotinPrime'Range;Prime(N*P):=False;endloop;endif;endloop;returnPrime;endGet_Primes;functionSum_Of(N:Natural)returnNaturalisImage:constantString:=Natural'Image(N);Sum:Natural:=0;beginforCharofImageloopSum:=Sum+(ifCharin'0'..'9'thenNatural'Value(""&Char)else0);endloop;returnSum;endSum_Of;packageNatural_Iois newAda.Text_Io.Integer_Io(Natural);useAda.Text_Io,Natural_Io;Prime:constantPrime_List:=Get_Primes;Count:Natural:=0;beginPut_Line("Additive primes <500:");forNinPrime'RangeloopifPrime(N)and thenPrime(Sum_Of(N))thenCount:=Count+1;Put(N,Width=>5);ifCountmodColumns=0thenNew_Line;endif;endif;endloop;New_Line;Put("There are ");Put(Count,Width=>2);Put(" additive primes.");New_Line;endAdditive_Primes;
Additive primes <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 487There are 54 additive primes.
begininteger procedure sumdigits(n); value n; integer n;begin integer q, sum; sum := 0; for sum := sum while n > 0 do begin q := entier(n / 10); sum := sum + (n - q * 10); n := q; end; sumdigits := sum;end;boolean procedure isprime(n);value n; integer n;begin if n < 2 then isprime := false else if n = entier(n / 2) * 2 then isprime := (n = 2) else begin comment - check odd divisors up to sqrt(n); integer i, limit; boolean divisible; i := 3; limit := entier(sqrt(n)); divisible := false; for i := i while i <= limit and not divisible do begin if entier(n / i) * i = n then divisible := true; i := i + 2 end; isprime := not divisible; end;end;integer i, count;outstring(1,"Looking up to 500 for additive primes\n");count := 0;for i := 2 step 1 until 500 do if isprime(i) then begin if isprime(sumdigits(i)) then begin outinteger(1,i); count := count + 1; if count = entier(count / 10) * 10 then outstring(1,"\n"); end; end;outstring(1,"\n");outinteger(1,count);outstring(1,"were found\n");end
Looking up to 500 for 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 54 were found
BEGIN # find additive primes - primes whose digit sum is also prime # # sieve the primes to max prime # PR read "primes.incl.a68" PR []BOOL prime = PRIMESIEVE 499; # find the additive primes # INT additive count := 0; FOR n TO UPB prime DO IF prime[ n ] THEN # have a prime # INT digit sum := 0; INT v := n; WHILE v > 0 DO digit sum +:= v MOD 10; v OVERAB 10 OD; IF prime( digit sum ) THEN # the digit sum is prime # print( ( " ", whole( n, -3 ) ) ); IF ( additive count +:= 1 ) MOD 20 = 0 THEN print( ( newline ) ) FI FI FI OD; print( ( newline, "Found ", whole( additive count, 0 ) ) ); print( ( " additive primes below ", whole( UPB prime + 1, 0 ), newline ) )END
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 487Found 54 additive primes below 500
BEGIN% RETURN N MOD M %INTEGER FUNCTION MOD(N, M);INTEGER N, M;BEGIN MOD := N - (N / M) * M;END;% RETURN 1 IF N IS PRIME, OTHERWISE 0 %INTEGER FUNCTION ISPRIME(N);INTEGER N;BEGIN IF N = 2 THEN ISPRIME := 1 ELSE IF (N < 2) OR (MOD(N,2) = 0) THEN ISPRIME := 0 ELSE % TEST ODD DIVISORS UP TO SQRT OF N % BEGIN INTEGER I, DIVISIBLE; I := 3; DIVISIBLE := 0; WHILE (I * I <= N) AND (DIVISIBLE = 0) DO BEGIN IF MOD(N,I) = 0 THEN DIVISIBLE := 1; I := I + 2; END; ISPRIME := 1 - DIVISIBLE; END;END; % RETURN THE SUM OF THE DIGITS OF N %INTEGER FUNCTION SUMDIGITS(N);INTEGER N;BEGIN INTEGER SUM; SUM := 0; WHILE N > 0 DO BEGIN SUM := SUM + MOD(N, 10); N := N / 10; END; SUMDIGITS := SUM;END;% LOOK FOR ADDITIVE PRIMES IN RANGE 1 TO 500 %INTEGER I, S, COUNT;COUNT := 0;FOR I := 1 STEP 1 UNTIL 500 DO BEGIN IF ISPRIME(I)=1 THEN BEGIN S := SUMDIGITS(I); IF ISPRIME(S)=1 THEN BEGIN WRITEON(I); COUNT := COUNT + 1; IF MOD(COUNT,8) = 0 THEN WRITE(""); END; END; END;WRITE(COUNT," ADDITIVE PRIMES WERE FOUND");END2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151 157 173 179 191 193 197 199 223 227 229 241 263 269 281 283 311 313 317 331 337 353 359 373 379 397 401 409 421 443 449 461 463 467 487 54 ADDITIVE PRIMES WERE FOUND
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 ) ; begin p( 1 ) := false; p( 2 ) := true; for i := 3 step 2 until n do p( i ) := true; for i := 4 step 2 until n do p( i ) := false; for i := 3 step 2 until truncate( sqrt( n ) ) do begin integer ii; ii := i + i; if p( i ) then for pr := i * i step ii until n do p( pr ) := false end for_i ; end Eratosthenes ; integer MAX_NUMBER; MAX_NUMBER := 500; begin logical array prime( 1 :: MAX_NUMBER ); integer aCount; % sieve the primes to MAX_NUMBER % Eratosthenes( prime, MAX_NUMBER ); % find the primes that are additive primes % aCount := 0; for i := 1 until MAX_NUMBER - 1 do begin if prime( i ) then begin integer dSum, v; v := i; dSum := 0; while v > 0 do begin dSum := dSum + v rem 10; v := v div 10 end while_v_gt_0 ; if prime( dSum ) then begin writeon( i_w := 4, s_w := 0, " ", i ); aCount := aCount + 1; if aCount rem 20 = 0 then write() end if_prime_dSum end if_prime_i end for_i ; write( i_w := 1, s_w := 0, "Found ", aCount, " additive primes below ", MAX_NUMBER ) endend.
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 487Found 54 additive primes below 500
((+⌿(4/10)⊤P)∊P)/P←(~P∊P∘.×P)/P←1↓⍳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
onsieveOfEratosthenes(limit)scriptopropertynumberList:{missing value}endscriptrepeatwithnfrom2tolimitsetendofo'snumberListtonendrepeatrepeatwithnfrom2to(limit^0.5)div1if(itemnofo'snumberListisn)thenrepeatwithmultiplefromn*ntolimitbynsetitemmultipleofo'snumberListtomissing valueendrepeatendifendrepeatreturno'snumberList'snumbersendsieveOfEratosthenesonsumOfDigits(n)-- n assumed to be a positive decimal integer.setsumtonmod10setntondiv10repeatuntil(n=0)setsumtosum+nmod10setntondiv10endrepeatreturnsumendsumOfDigitsonadditivePrimes(limit)scriptopropertyprimes:sieveOfEratosthenes(limit)propertyadditives:{}endscriptrepeatwithpino'sprimesif(sumOfDigits(p)is ino'sprimes)thensetendofo'sadditivestop'scontentsendrepeatreturno'sadditivesendadditivePrimes-- Task code:telladditivePrimes(499)toreturn{|additivePrimes<500|:it,numberThereof:count}
{|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}
/* ARM assembly Raspberry PI *//* program additivePrime.s */ /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include *//* for constantes see task include a file in arm assembly *//************************************//* Constantes *//************************************/.include "../constantes.inc" .equ MAXI, 500 /*********************************//* Initialized data *//*********************************/.dataszMessResult: .asciz "Prime : @ \n"szMessCounter: .asciz "Number found : @ \n" szCarriageReturn: .asciz "\n" /*********************************//* UnInitialized data *//*********************************/.bss sZoneConv: .skip 24TablePrime: .skip 4 * MAXI /*********************************//* code section *//*********************************/.text.global main main: @ entry of program bl createArrayPrime mov r5,r0 @ prime number ldr r4,iAdrTablePrime @ address prime table mov r10,#0 @ init counter mov r6,#0 @ indice1: ldr r2,[r4,r6,lsl #2] @ load prime mov r9,r2 @ save prime mov r7,#0 @ init digit sum mov r1,#10 @ divisor2: @ begin loop mov r0,r2 @ dividende bl division add r7,r7,r3 @ add digit to digit sum cmp r2,#0 @ quotient null ? bne 2b @ no -> comppute other digit mov r8,#1 @ indice4: @ prime search loop cmp r8,r5 @ maxi ? bge 5f @ yes ldr r0,[r4,r8,lsl #2] @ load prime cmp r0,r7 @ prime >= digit sum ? addlt r8,r8,#1 @ no -> increment indice blt 4b @ and loop bne 5f @ > mov r0,r9 @ equal bl displayPrime add r10,r10,#1 @ increment counter5: add r6,r6,#1 @ increment first indice cmp r6,r5 @ maxi ? blt 1b @ and loop mov r0,r10 @ number counter ldr r1,iAdrsZoneConv bl conversion10 @ call décimal conversion ldr r0,iAdrszMessCounter ldr r1,iAdrsZoneConv @ insert conversion in message bl strInsertAtCharInc bl affichageMess @ display message 100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system calliAdrszCarriageReturn: .int szCarriageReturniAdrszMessResult: .int szMessResultiAdrszMessCounter: .int szMessCounteriAdrTablePrime: .int TablePrime/******************************************************************//* créate prime array */ /******************************************************************/createArrayPrime: push {r1-r7,lr} @ save registers ldr r4,iAdrTablePrime @ address prime table mov r0,#1 str r0,[r4] @ store 1 in array mov r0,#2 str r0,[r4,#4] @ store 2 in array mov r0,#3 str r0,[r4,#8] @ store 3 in array mov r5,#3 @ prine counter mov r7,#5 @ first number to test1: mov r6,#1 @ indice2: mov r0,r7 @ dividende ldr r1,[r4,r6,lsl #2] @ load divisor bl division cmp r3,#0 @ null remainder ? beq 3f @ yes -> end loop cmp r2,r1 @ quotient < divisor strlt r7,[r4,r5,lsl #2] @ dividende is prime store in array addlt r5,r5,#1 @ increment counter blt 3f @ and end loop add r6,r6,#1 @ else increment indice cmp r6,r5 @ maxi ? blt 2b @ no -> loop3: add r7,#2 @ other odd number cmp r7,#MAXI @ maxi ? blt 1b @ no -> loop mov r0,r5 @ return counter100: pop {r1-r7,pc}/******************************************************************//* Display prime table elements */ /******************************************************************//* r0 contains the prime */displayPrime: push {r1,lr} @ save registers ldr r1,iAdrsZoneConv bl conversion10 @ call décimal conversion ldr r0,iAdrszMessResult ldr r1,iAdrsZoneConv @ insert conversion in message bl strInsertAtCharInc bl affichageMess @ display message100: pop {r1,pc}iAdrsZoneConv: .int sZoneConv /***************************************************//* ROUTINES INCLUDE *//***************************************************/.include "../affichage.inc"Prime : 2Prime : 3Prime : 5Prime : 7Prime : 11Prime : 23Prime : 29Prime : 41Prime : 43Prime : 47Prime : 61Prime : 67Prime : 83Prime : 89Prime : 101Prime : 113Prime : 131Prime : 137Prime : 139Prime : 151Prime : 157Prime : 173Prime : 179Prime : 191Prime : 193Prime : 197Prime : 199Prime : 223Prime : 227Prime : 229Prime : 241Prime : 263Prime : 269Prime : 281Prime : 283Prime : 311Prime : 313Prime : 317Prime : 331Prime : 337Prime : 353Prime : 359Prime : 373Prime : 379Prime : 397Prime : 401Prime : 409Prime : 421Prime : 443Prime : 449Prime : 461Prime : 463Prime : 467Prime : 487Number found : 54
additives:select2..500'x->and?prime?xprime?sumdigitsxloopsplit.every:10additives'a->printmapa=>[padto:string&4]print["\nFound"sizeadditives"additive primes up to 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 Found 54 additive primes up to 500
# syntax: GAWK -f ADDITIVE_PRIMES.AWKBEGIN{start=1stop=500for(i=start;i<=stop;i++){if(is_prime(i)&&is_prime(sum_digits(i))){printf("%4d%1s",i,++count%10?"":"\n")}}printf("\nAdditive primes %d-%d: %d\n",start,stop,count)exit(0)}functionis_prime(x,i){if(x<=1){return(0)}for(i=2;i<=int(sqrt(x));i++){if(x%i==0){return(0)}}return(1)}functionsum_digits(n,i,sum){for(i=1;i<=length(n);i++){sum+=substr(n,i,1)}return(sum)}
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 487Additive primes 1-500: 54
importballerina/io;functionsumDigits(intm)returnsint{intn=m;// make mutableintsum=0;whilen>0{sum+=n%10;n/=10;}returnsum;}functionisPrime(intn)returnsboolean{ifn<2{returnfalse;}ifn%2==0{returnn==2;}ifn%3==0{returnn==3;}intd=5;whiled*d<=n{ifn%d==0{returnfalse;}d+=2;ifn%d==0{returnfalse;}d+=4;}returntrue;}functiongetPrimes(intn)returnsint[]{ifn<2{return[];}ifn==2{return[2];}intk=(n-3)/2+1;boolean[]marked=[];marked.setLength(k);foreachintiin0..<k{marked[i]=true;}floatf=(<float>n).sqrt().floor();intlim=(<int>f-3)/2+1;foreachintiin0..<lim{ifmarked[i]{intp=2*i+3;ints=(p*p-3)/2;intj=s;whilej<k{marked[j]=false;j+=p;}}}int[]primes=[2];foreachintiin0..<k{ifmarked[i]{primes.push(2*i+3);}}returnprimes;}publicfunctionmain(){io:println("Additive primes less than 500:");int[]primes=getPrimes(499);intcount=0;foreachintpinprimes{ifisPrime(sumDigits(p)){count+=1;stringps=p.toString().padStart(3);io:print(ps," ");ifcount%10==0{io:println();}}}io:println("\n\n",count," additive primes found.");}
Additive primes less than 500: 2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151 157 173 179 191 193 197 199 223 227 229 241 263 269 281 283 311 313 317 331 337 353 359 373 379 397 401 409 421 443 449 461 463 467 487 54 additive primes found.
10DEFINTA-Z:E=50020DIMP(E):P(0)=-1:P(1)=-130FORI=2TOSQR(E)40IFNOTP(I)THENFORJ=I*2TOESTEPI:P(J)=-1:NEXT50NEXT60FORI=BTOE:IFP(I)GOTO10070J=I:S=080IFJ>0THENS=S+JMOD10:J=J\10:GOTO8090IFNOTP(S)THENN=N+1:PRINTI,100NEXT110PRINT:PRINTN;" additive primes found below ";E
2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151 157 173 179 191 193 197 199 223 227 229 241 263 269 281 283 311 313 317 331 337 353 359 373 379 397 401 409 421 443 449 461 463 467 487 54 additive primes found below 500
0E=5001F=E-1:L=LEN(STR$(F))+1:FORI=2TOL:S$=S$+CHR$(32):NEXTI:DIMP(E):P(0)=-1:P(1)=-1:FORI=2TOSQR(F):IFNOTP(I)THENFORJ=I*2TOESTEPI:P(J)=-1:NEXTJ2NEXTI:FORI=BTOF:IFNOTP(I)THENGOSUB43NEXTI:PRINT:PRINTN" ADDITIVE PRIMES FOUND BELOW "E;:END4S=0:IFITHENFORJ=ITO0STEP0:J1=INT(J/10):S=S+(J-J1*10):J=J1:NEXTJ5IFNOTP(S)THENN=N+1:PRINTRIGHT$(S$+STR$(I),L);6RETURN
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 48754 ADDITIVE PRIMES FOUND BELOW 500
print"Prime","Digit Sum"fori=2to499ifisprime(i)thens=digSum(i)ifisPrime(s)thenprinti,sendifnextiendfunctionisPrime(v)ifv<2thenreturnFalseifvmod2=0thenreturnv=2ifvmod3=0thenreturnv=3d=5whiled*d<=vifvmodd=0thenreturnFalseelsed+=2endwhilereturnTrueendfunctionfunctiondigsum(n)s=0whilens+=nmod10n/=10endwhilereturnsendfunction
get "libhdr"manifest $( limit = 500 $) let dsum(n) = n=0 -> 0, dsum(n/10) + n rem 10let sieve(prime, n) be$( 0!prime := false 1!prime := false for i=2 to n do i!prime := true for i=2 to n/2 if i!prime $( let j=i+i while j<=n $( j!prime := false j := j+i $) $)$)let additive(prime, n) = n!prime & dsum(n)!primelet start() be$( let prime = vec limit let num = 0 sieve(prime, limit) for i=2 to limit if additive(prime,i) $( writed(i,5) num := num + 1 if num rem 10 = 0 then wrch('*N') $) writef("*N*NFound %N additive primes < %N.*N", num, limit)$)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 487Found 54 additive primes < 500.
#include<stdbool.h>#include<stdio.h>#include<string.h>voidmemoizeIsPrime(bool*result,constintN){result[2]=true;result[3]=true;intprime[N];prime[0]=3;intend=1;for(intn=5;n<N;n+=2){booln_is_prime=true;for(inti=0;i<end;++i){constintPRIME=prime[i];if(n%PRIME==0){n_is_prime=false;break;}if(PRIME*PRIME>n){break;}}if(n_is_prime){prime[end++]=n;result[n]=true;}}}/* memoizeIsPrime */intsumOfDecimalDigits(intn){intsum=0;while(n>0){sum+=n%10;n/=10;}returnsum;}/* sumOfDecimalDigits */intmain(void){constintN=500;printf("Rosetta Code: additive primes less than %d:\n",N);boolis_prime[N];memset(is_prime,0,sizeof(is_prime));memoizeIsPrime(is_prime,N);printf(" 2");intcount=1;for(inti=3;i<N;i+=2){if(is_prime[i]&&is_prime[sumOfDecimalDigits(i)]){printf("%4d",i);++count;if((count%10)==0){printf("\n");}}}printf("\nThose were %d additive primes.\n",count);return0;}/* main */
Rosetta Code: additive primes less than 500: 2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151 157 173 179 191 193 197 199 223 227 229 241 263 269 281 283 311 313 317 331 337 353 359 373 379 397 401 409 421 443 449 461 463 467 487Those were 54 additive primes.
#include<iomanip>#include<iostream>boolis_prime(unsignedintn){if(n<2)returnfalse;if(n%2==0)returnn==2;if(n%3==0)returnn==3;for(unsignedintp=5;p*p<=n;p+=4){if(n%p==0)returnfalse;p+=2;if(n%p==0)returnfalse;}returntrue;}unsignedintdigit_sum(unsignedintn){unsignedintsum=0;for(;n>0;n/=10)sum+=n%10;returnsum;}intmain(){constunsignedintlimit=500;std::cout<<"Additive primes less than "<<limit<<":\n";unsignedintcount=0;for(unsignedintn=1;n<limit;++n){if(is_prime(digit_sum(n))&&is_prime(n)){std::cout<<std::setw(3)<<n;if(++count%10==0)std::cout<<'\n';elsestd::cout<<' ';}}std::cout<<'\n'<<count<<" additive primes found.\n";}
Additive primes less than 500: 2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151157 173 179 191 193 197 199 223 227 229241 263 269 281 283 311 313 317 331 337353 359 373 379 397 401 409 421 443 449461 463 467 487 54 additive primes found.
internalclassProgram{privatestaticvoidMain(string[]args){longprimeCandidate=1;longadditivePrimeCount=0;Console.WriteLine("Additive Primes");while(primeCandidate<500){if(IsAdditivePrime(primeCandidate)){additivePrimeCount++;Console.Write($"{primeCandidate,-3} ");if(additivePrimeCount%10==0){Console.WriteLine();}}primeCandidate++;}Console.WriteLine();Console.WriteLine($"Found {additivePrimeCount} additive primes less than 500");}privatestaticboolIsAdditivePrime(longnumber){if(IsPrime(number)&&IsPrime(DigitSum(number))){returntrue;}returnfalse;}privatestaticboolIsPrime(longnumber){if(number<2){returnfalse;}if(number%2==0){returnnumber==2;}if(number%3==0){returnnumber==3;}intdelta=2;longk=5;while(k*k<=number){if(number%k==0){returnfalse;}k+=delta;delta=6-delta;}returntrue;}privatestaticlongDigitSum(longn){longsum=0;while(n>0){sum+=n%10;n/=10;}returnsum;}}
Additive Primes2 3 5 7 11 23 29 41 43 4761 67 83 89 101 113 131 137 139 151157 173 179 191 193 197 199 223 227 229241 263 269 281 283 311 313 317 331 337353 359 373 379 397 401 409 421 443 449461 463 467 487Found 54 additive primes less than 500
% Sieve of Erastothenes% Returns an array [1..max] marking the primessieve = proc (max: int) returns (array[bool]) prime: array[bool] := array[bool]$fill(1, max, true) prime[1] := false for p: int in int$from_to(2, max/2) do if prime[p] then for comp: int in int$from_to_by(p*2, max, p) do prime[comp] := false end end end return(prime)end sieve% Sum the digits of a numberdigit_sum = proc (n: int) returns (int) sum: int := 0 while n ~= 0 do sum := sum + n // 10 n := n / 10 end return(sum)end digit_sum start_up = proc () max = 500 po: stream := stream$primary_output() count: int := 0 prime: array[bool] := sieve(max) for i: int in array[bool]$indexes(prime) do if prime[i] cand prime[digit_sum(i)] then count := count + 1 stream$putright(po, int$unparse(i), 5) if count//10 = 0 then stream$putl(po, "") end end end stream$putl(po, "\nFound " || int$unparse(count) || " additive primes < " || int$unparse(max)) end start_up
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 487Found 54 additive primes < 500
IDENTIFICATIONDIVISION.PROGRAM-ID.ADDITIVE-PRIMES.DATADIVISION.WORKING-STORAGESECTION.01VARIABLES.03MAXIMUMPIC 999.03AMOUNTPIC 999.03CANDIDATEPIC 999.03DIGITPIC 9OCCURS3TIMES,REDEFINESCANDIDATE.03DIGITSUMPIC 99.01PRIME-DATA.03COMPOSITE-FLAGPIC XOCCURS500TIMES.88PRIMEVALUE' '.03SIEVE-PRIMEPIC 999.03SIEVE-COMP-STARTPIC 999.03SIEVE-COMPPIC 999.03SIEVE-MAXPIC 999.01OUT-FMT.03NUM-FMTPIC ZZZ9.03OUT-LINEPIC X(40).03OUT-PTRPIC 99.PROCEDUREDIVISION.BEGIN.MOVE500TOMAXIMUM.MOVE1TOOUT-PTR.PERFORMSIEVE.MOVEZEROTOAMOUNT.PERFORMTEST-NUMBERVARYINGCANDIDATEFROM2BY1UNTILCANDIDATEISGREATERTHANMAXIMUM.DISPLAYOUT-LINE.DISPLAYSPACES.MOVEAMOUNTTONUM-FMT.DISPLAY'Amount of additive primes found: 'NUM-FMT.STOPRUN.TEST-NUMBER.ADDDIGIT(1),DIGIT(2),DIGIT(3)GIVINGDIGITSUM.IFPRIME(CANDIDATE)ANDPRIME(DIGITSUM),ADD1TOAMOUNT,PERFORMWRITE-NUMBER.WRITE-NUMBER.MOVECANDIDATETONUM-FMT.STRINGNUM-FMTDELIMITEDBYSIZEINTOOUT-LINEWITHPOINTEROUT-PTR.IFOUT-PTRISGREATERTHAN40,DISPLAYOUT-LINE,MOVESPACESTOOUT-LINE,MOVE1TOOUT-PTR.SIEVE.MOVESPACESTOPRIME-DATA.DIVIDEMAXIMUMBY2GIVINGSIEVE-MAX.PERFORMSIEVE-OUTER-LOOPVARYINGSIEVE-PRIMEFROM2BY1UNTILSIEVE-PRIMEISGREATERTHANSIEVE-MAX.SIEVE-OUTER-LOOP.IFPRIME(SIEVE-PRIME),MULTIPLYSIEVE-PRIMEBY2GIVINGSIEVE-COMP-START,PERFORMSIEVE-INNER-LOOPVARYINGSIEVE-COMPFROMSIEVE-COMP-STARTBYSIEVE-PRIMEUNTILSIEVE-COMPISGREATERTHANMAXIMUM.SIEVE-INNER-LOOP.MOVE'X'TOCOMPOSITE-FLAG(SIEVE-COMP).
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 487Amount of additive primes found: 54
(defunsum-of-digits(n)"Return the sum of the digits of a number"(do*((sum0(+sumrem))rem)((zeropn)sum)(multiple-value-setq(nrem)(floorn10))))(defunadditive-primep(n)(and(primepn)(primep(sum-of-digitsn)))); To test if a number is prime we can use a number of different methods. Here I use Wilson's Theorem (see Primality by Wilson's theorem):(defunprimep(n)(unless(zeropn)(zerop(mod(1+(factorial(1-n)))n))))(defunfactorial(n)(if(<n2)1(*n(factorial(1-n)))))
(dotimes (i 500) (when (additive-primep i) (princ i) (princ " ")))1 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
# Fast/simple way to generate primes for small values.# Uses P3 Prime Generator (PG) and its Prime Generator Sequence (PGS).defprime?(n)# P3 Prime Generator primality testreturnfalseunless(n|1==3ifn<5)||(n%6)|4==5sqrt_n=Math.isqrt(n)# For Crystal < 1.2.0 use Math.sqrt(n).to_ipc=typeof(n).new(5)whilepc<=sqrt_nreturnfalseifn%pc==0||n%(pc+2)==0pc+=6endtrueenddefadditive_primes(n)primes=[2,3]pc,inc=5,2whilepc<nprimes<<pcifprime?(pc)&&prime?(pc.digits.sum)pc+=inc;inc^=0b110# generate P3 sequence: 5 7 11 13 17 19 ...endprimes# list of additive primes <= nendnn=500addprimes=additive_primes(nn)maxdigits=addprimes.last.digits.sizeaddprimes.each_with_index{|n,idx|printf"%*d ",maxdigits,n;print"\n"ifidx%10==9}# more efficient#addprimes.each_with_index { |n, idx| print "%#{maxdigits}d " % n; print "\n" if idx % 10 == 9} # alternativelyputs"\n#{addprimes.size} additive primes below#{nn}."putsnn=5000addprimes=additive_primes(nn)maxdigits=addprimes.last.digits.sizeaddprimes.each_with_index{|n,idx|printf"%*d ",maxdigits,n;print"\n"ifidx%10==9}# more efficientputs"\n#{addprimes.size} additive primes below#{nn}."
2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151 157 173 179 191 193 197 199 223 227 229 241 263 269 281 283 311 313 317 331 337 353 359 373 379 397 401 409 421 443 449 461 463 467 487 54 additive primes below 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 557 571 577 593 599 601 607 641 643 647 661 683 719 733 739 751 757 773 797 809 821 823 827 829 863 881 883 887 911 919 937 953 971 977 991 1013 1019 1031 1033 1039 1051 1091 1093 1097 1103 1109 1123 1129 1163 1181 1187 1213 1217 1231 1237 1259 1277 1279 1291 1297 1301 1303 1307 1321 1327 1361 1367 1381 1433 1439 1451 1453 1459 1471 1493 1499 1523 1543 1549 1567 1583 1613 1619 1637 1657 1693 1697 1709 1721 1723 1741 1747 1783 1787 1811 1831 1871 1873 1877 1901 1907 1949 2003 2027 2029 2063 2069 2081 2083 2087 2089 2111 2113 2131 2137 2153 2179 2203 2207 2221 2243 2267 2269 2281 2287 2311 2333 2339 2351 2357 2371 2377 2393 2399 2423 2441 2447 2467 2531 2539 2551 2557 2579 2591 2593 2609 2621 2647 2663 2683 2687 2711 2713 2719 2731 2753 2777 2791 2801 2803 2843 2861 2917 2939 2953 2957 2971 2999 3011 3019 3037 3079 3109 3121 3163 3167 3169 3181 3187 3217 3251 3253 3257 3259 3271 3299 3301 3307 3323 3329 3343 3347 3361 3389 3413 3433 3457 3491 3527 3529 3541 3547 3581 3583 3613 3617 3631 3637 3659 3671 3673 3677 3691 3701 3709 3727 3761 3767 3833 3851 3853 3907 3923 3929 3943 3947 3989 4001 4003 4007 4021 4027 4049 4111 4133 4139 4153 4157 4159 4177 4201 4229 4241 4243 4261 4283 4289 4337 4339 4357 4373 4391 4397 4409 4421 4423 4441 4447 4463 4481 4483 4513 4517 4519 4591 4603 4621 4643 4649 4663 4733 4751 4793 4799 4801 4861 4889 4919 4931 4933 4937 4951 4973 4999 338 additive primes below 5000.
import'dart:math';voidmain(){constlimit=500;print('Additive primes less than$limit :');intcount=0;for(intn=1;n<limit;++n){if(isPrime(digit_sum(n))&&isPrime(n)){print('$n');++count;}}print('$count additive primes found.');}boolisPrime(intn){if(n<=1)returnfalse;if(n==2)returntrue;for(inti=2;i<=sqrt(n);++i){if(n%i==0)returnfalse;}returntrue;}intdigit_sum(intn){intsum=0;for(intm=n;m>0;m~/=10)sum+=m%10;returnsum;}
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.
{These routines would normally be in libraries but are shown here for clarity}functionIsPrime(N:int64):boolean;{Fast, optimised prime test}varI,Stop:int64;beginif(N=2)or(N=3)thenResult:=trueelseif(n<=1)or((nmod2)=0)or((nmod3)=0)thenResult:=falseelsebeginI:=5;Stop:=Trunc(sqrt(N+0.0));Result:=False;whileI<=Stopdobeginif((NmodI)=0)or((Nmod(I+2))=0)thenexit;Inc(I,6);end;Result:=True;end;end;functionSumDigits(N:integer):integer;{Sum the integers in a number}varT:integer;beginResult:=0;repeatbeginT:=Nmod10;N:=Ndiv10;Result:=Result+T;enduntilN<1;end;procedureShowDigitSumPrime(Memo:TMemo);varN,Sum,Cnt:integer;varNS,S:string;beginCnt:=0;S:='';forN:=1to500-1doifIsPrime(N)thenbeginSum:=SumDigits(N);ifIsPrime(Sum)thenbeginInc(Cnt);S:=S+Format('%6d',[N]);if(Cntmod8)=0thenS:=S+CRLF;end;end;Memo.Lines.Add(S);Memo.Lines.Add('Count = '+IntToStr(Cnt));end;
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 487Count = 54Elapsed Time: 2.812 ms.
SeePascal.
proc sieve([*] bool prime) void: word max, p, c; max := dim(prime,1)-1; prime[0] := false; prime[1] := false; for p from 2 upto max do prime[p] := true od; for p from 2 upto max/2 do for c from p*2 by p upto max do prime[c] := false od odcorpproc digit_sum(word num) byte: byte sum; sum := 0; while sum := sum + num % 10; num := num / 10; num /= 0 do od; sumcorpproc main() void: word MAX = 500; word p, n; [MAX]bool prime; sieve(prime); n := 0; for p from 2 upto MAX-1 do if prime[p] and prime[digit_sum(p)] then write(p:4); n := n + 1; if n % 20 = 0 then writeln() fi fi od; writeln(); writeln("There are ", n, " additive primes below ", MAX)corp2 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 487There are 54 additive primes below 500
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 & " " ..
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
main(_)->AddPrimes=[N||N<-lists:seq(2,500),isprime(N)andalsoisprime(digitsum(N))],io:format("The additive primes up to 500 are:~n~p~n~n",[AddPrimes]),io:format("There are~b of them.~n",[length(AddPrimes)]).isprime(N)whenN<2->false;isprime(N)->isprime(N,2,0,<<1,2,2,4,2,4,2,4,6,2,6>>).isprime(N,D,J,Wheel)whenJ=:=byte_size(Wheel)->isprime(N,D,3,Wheel);isprime(N,D,_,_)whenD*D>N->true;isprime(N,D,_,_)whenNremD=:=0->false;isprime(N,D,J,Wheel)->isprime(N,D+binary:at(Wheel,J),J+1,Wheel).digitsum(N)->digitsum(N,0).digitsum(0,S)->S;digitsum(N,S)->digitsum(Ndiv10,S+Nrem10).
The additive primes up to 500 are:[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 of them.
This task usesExtensible Prime Generator (F#)
// Additive Primes. Nigel Galloway: March 22nd., 2021letrecfNg=functionnwhenn<10->n+g|n->fN(g+n%10)(n/10)primes32()|>Seq.takeWhile((>)500)|>Seq.filter(fN0>>isPrime)|>Seq.iter(printf"%d ");printfn""
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
USING:formattinggroupingiokernelmathmath.primesprettyprintsequences;:sum-digits(n--sum)0swap[10/modrot+swap]until-zero;499primes-upto[sum-digitsprime?]filter[9groupsimple-table.nl][length"Found %d additive primes < 500.\n"printf]bi
2 3 5 7 11 23 29 41 4347 61 67 83 89 101 113 131 137139 151 157 173 179 191 193 197 199223 227 229 241 263 269 281 283 311313 317 331 337 353 359 373 379 397401 409 421 443 449 461 463 467 487Found 54 additive primes < 500.
Function Digsum(n) = digsum := 0; while n>0 do digsum := digsum + n|10; n:=n\10; od; digsum.;nadd := 0;!!'Additive primes below 500 are';for p=1 to 500 do if Isprime(p) and Isprime(Digsum(p)) then !!(p,' -> ',Digsum(p)); nadd := nadd+1; fi od;!!('There were ',nadd);Additive primes below 500 are
2 -> 23 -> 35 -> 57 -> 711 -> 223 -> 529 -> 1141 -> 543 -> 747 -> 1161 -> 767 -> 1383 -> 1189 -> 17101 -> 2113 -> 5131 -> 5137 -> 11139 -> 13151 -> 7157 -> 13173 -> 11179 -> 17191 -> 11193 -> 13197 -> 17199 -> 19223 -> 7227 -> 11229 -> 13241 -> 7263 -> 11269 -> 17281 -> 11283 -> 13311 -> 5313 -> 7317 -> 11331 -> 7337 -> 13353 -> 11359 -> 17373 -> 13379 -> 19397 -> 19401 -> 5409 -> 13421 -> 7443 -> 11449 -> 17461 -> 11463 -> 13467 -> 17487 -> 19There were 54
:prime?( n -- ? )here+c@0=;:notprime!( n -- )here+1swapc!;:prime_sieve( n -- )hereovererase0notprime!1notprime!2begin2dupdup*>whiledupprime?if2dupdup*doinotprime!dup+loopthen1+repeat2drop;:digit_sum( u -- u )dup10<ifexitthen10/modrecurse+;:print_additive_primes( n -- )."Additive primes less than"dup1.r.":"crdupprime_sieve0swap1doiprime?ifidigit_sumprime?ifi3.r1+dup10mod0=ifcrelsespacethenthenthenloopcr.."additive primes found."cr;500print_additive_primesbye
Additive primes less than 500: 2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151157 173 179 191 193 197 199 223 227 229241 263 269 281 283 311 313 317 331 337353 359 373 379 397 401 409 421 443 449461 463 467 487 54 additive primes found.
programAdditivePrimesimplicit noneinteger::i,j,digit_sum,countlogical::is_prime! Arrays to track prime numbers and additive primeslogical,dimension(500)::prime_checklogical,dimension(500)::additive_prime_check! Initialize arraysprime_check=.true.prime_check(1)=.false.additive_prime_check=.false.! Sieve of Eratosthenes to find primesdoi=2,int(sqrt(real(500)))if(prime_check(i))then doj=i*i,500,iprime_check(j)=.false.end do end if end do! Find additive primescount=0doi=2,500if(prime_check(i))then! Calculate digit sumdigit_sum=sum_digits(i)! Check if digit sum is also primeif(prime_check(digit_sum))thenadditive_prime_check(i)=.true.count=count+1end if end if end do! Print resultsprint*,"Additive Primes less than 500:"doi=2,500if(additive_prime_check(i))then print*,iend if end do print*,"Total number of additive primes:",countcontains! Function to calculate sum of digitsfunctionsum_digits(num)result(total)integer,intent(in)::numinteger::total,temp_numtotal=0temp_num=numdo while(temp_num>0)total=total+mod(temp_num,10)temp_num=temp_num/10end do end functionsum_digitsend programAdditivePrimes
Additive Primes less than 500: 2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151 157 173 179 191 193 197 199 223 227 229 241 263 269 281 283 311 313 317 331 337 353 359 373 379 397 401 409 421 443 449 461 463 467 487 Total number of additive primes: 54
As with the other special primes tasks, use one of the primality testing algorithms as an include.
#include"isprime.bas"functiondigsum(nasuinteger)asuintegerdimasuintegerswhilens+=nmod10n\=10wendreturnsendfunctiondimasuintegersprint"Prime","Digit Sum"foriasuinteger=2to499ifisprime(i)thens=digsum(i)ifisprime(s)thenprinti,sendifendifnexti
Prime Digit Sum2 23 35 57 711 223 529 1141 543 747 1161 767 1383 1189 17101 2113 5131 5137 11139 13151 7157 13173 11179 17191 11193 13197 17199 19223 7227 11229 13241 7263 11269 17281 11283 13311 5313 7317 11331 7337 13353 11359 17373 13379 19397 19401 5409 13421 7443 11449 17461 11463 13467 17487 19
Using Sieve of Eratosthenes to find all primes upto 500,then go through the list, sum digits and check for prime
ProgramAdditivePrimes;Constmax_number=500;Varis_prime:arrayOfBoolean;Proceduresieve(Vararr:ArrayOfboolean);{use Sieve of Eratosthenes to find all primes to max number}Vari,j:NativeUInt;BeginFori:=2Tohigh(arr)Doarr[i]:=True;// set all bits to be TrueFori:=2Tohigh(arr)DoBeginIf(arr[i])ThenForj:=2To(high(arr)Divi)Doarr[i*j]:=False;End;End;FunctionGetSumOfDigits(num:NativeUInt):longint;{calcualte the sum of digits of a number}Varsum:longint=0;dummy:NativeUInt;BeginRepeatdummy:=num;num:=numDiv10;Inc(sum,dummy-(numSHL3+numSHL1));Untilnum<1;GetSumOfDigits:=sum;End;Varx:NativeUInt=2;{first prime}counter:longint=0;Beginsetlength(is_prime,max_number);//set length of array to max_numberSieve(is_prime);//apply Sieve{since 2 is the only even prime, let's do it separate}Ifis_prime[x]Andis_prime[GetSumOfDigits(x)]ThenBeginwrite(x:4);inc(counter);End;inc(x);Whilex<max_numberDoBeginIfis_prime[x]Andis_prime[GetSumOfDigits(x)]ThenBeginifcountermod10=0thenwriteln();write(x:4);inc(counter);End;inc(x,2);End;writeln();writeln();writeln(counter,' additive primes found.');End.
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 48754 additive primes found.
vals = toArray[select[primes[2, 500], {|x| isPrime[sum[integerDigits[x]]]}]]println[formatTable[columnize[vals, 10]]]println["\n" + length[vals] + " values found."]2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151157 173 179 191 193 197 199 223 227 229241 263 269 281 283 311 313 317 331 337353 359 373 379 397 401 409 421 443 449461 463 467 48754 values found.
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 nextend fn = resultlocal fn DigSum( n as NSUInteger ) as NSUInteger NSUInteger s = 0 while ( n > 0 ) s += ( n mod 10 ) n /= 10 wendend fn = svoid 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, nend fnfn AdditivePrimes( 500 )HandleEvents
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.
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.
Programs in Fōrmulæ are created/edited online in itswebsite.
Inthis page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.
Solution
Test case 1. Write a program to determine all additive primes less than 500.
Test case 2. Show the number of additive primes.
packagemainimport"fmt"funcisPrime(nint)bool{switch{casen<2:returnfalsecasen%2==0:returnn==2casen%3==0:returnn==3default:d:=5ford*d<=n{ifn%d==0{returnfalse}d+=2ifn%d==0{returnfalse}d+=4}returntrue}}funcsumDigits(nint)int{sum:=0forn>0{sum+=n%10n/=10}returnsum}funcmain(){fmt.Println("Additive primes less than 500:")i:=2count:=0for{ifisPrime(i)&&isPrime(sumDigits(i)){count++fmt.Printf("%3d ",i)ifcount%10==0{fmt.Println()}}ifi>2{i+=2}else{i++}ifi>499{break}}fmt.Printf("\n\n%d additive primes found.\n",count)}
Additive primes less than 500: 2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151 157 173 179 191 193 197 199 223 227 229 241 263 269 281 283 311 313 317 331 337 353 359 373 379 397 401 409 421 443 449 461 463 467 487 54 additive primes found.
hasDivisor :: (int * int) -> boolhasDivisor x = match x with | (n, d) -> if (d * d > n) then false else if (n % d == 0) then true else hasDivisor((n, d + 1))isPrime :: int -> boolisPrime n = if (n < 2) then false else not(hasDivisor((n, 2)))digitSum :: int -> intdigitSum n = if (n < 10) then n else (n % 10) + digitSum(n / 10)[n | n <- [2..500], isPrime(n) and isPrime(digitSum(n))]
[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]
The following works in both languages:
linkfactorsproceduremain(A)limit:=\A[1]|500everyp:=prime()doifp<500thenwrites(" ",additive(p))elsebreakwrite()endprocedureadditive(a)a?(sum:=0,whilesum+:=move(1))return(isprime(sum),a)end
Output:
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
(#~1p:[:+/@|:10&#.inv)i.&.(p:inv)500235711232941434761678389101113131137139151157173179191193197199223227229241263269281283311313317331337353359373379397401409421443449461463467487
publicclassadditivePrimes{publicstaticvoidmain(String[]args){intadditive_primes=0;for(inti=2;i<500;i++){if(isPrime(i)&&isPrime(digitSum(i))){additive_primes++;System.out.print(i+" ");}}System.out.print("\nFound "+additive_primes+" additive primes less than 500");}staticbooleanisPrime(intn){intcounter=1;if(n<2||(n!=2&&n%2==0)||(n!=3&&n%3==0)){returnfalse;}while(counter*6-1<=Math.sqrt(n)){if(n%(counter*6-1)==0||n%(counter*6+1)==0){returnfalse;}else{counter++;}}returntrue;}staticintdigitSum(intn){intsum=0;while(n>0){sum+=n%10;n/=10;}returnsum;}}
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
Works with gojq, the Go implementation of jq
Preliminaries
def is_prime: . as $n | if ($n < 2) then false elif ($n % 2 == 0) then $n == 2 elif ($n % 3 == 0) then $n == 3 elif ($n % 5 == 0) then $n == 5 elif ($n % 7 == 0) then $n == 7 elif ($n % 11 == 0) then $n == 11 elif ($n % 13 == 0) then $n == 13 elif ($n % 17 == 0) then $n == 17 elif ($n % 19 == 0) then $n == 19 else {i:23} | until( (.i * .i) > $n or ($n % .i == 0); .i += 2) | .i * .i > $n end;# Emit an array of primes less than `.`def primes: if . < 2 then [] else [2] + [range(3; .; 2) | select(is_prime)] end;def add(s): reduce s as $x (null; . + $x);def sumdigits: add(tostring | explode[] | [.] | implode | tonumber);# Pretty-printingdef nwise($n): def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end; n;def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;The task
# Input: a number n# Output: an array of additive primes less than ndef additive_primes: primes | . as $primes | reduce .[] as $p (null; ( $p | sumdigits ) as $sum | if (($primes | bsearch($sum)) > -1) then . + [$p] else . end );"Erdős primes under 500:",(500 | additive_primes | ((nwise(10) | map(lpad(4)) | join(" ")), "\n\(length) additive primes found."))Erdős 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 48754 additive primes found.
Naive solution which doesn't rely on advanced number theoretic libraries.
importData.List(unfoldr)-- infinite list of primesprimes=2:sieve[3,5..]wheresieve(x:xs)=x:sieve(filter(\y->y`mod`x/=0)xs)-- primarity test, effective for numbers less then billionisPrimen=all(\p->n`mod`p/=0)$takeWhile(<sqrtN)primeswheresqrtN=round.sqrt.fromIntegral$n-- decimal digits of a numberdigits=unfoldrfwheref0=Nothingfn=let(q,r)=divModn10inJust(r,q)-- test for an additive primeisAdditivePrimen=isPrimen&&(isPrime.sum.digits)n
The task
λ> isPrime 12373Trueλ> isAdditivePrime 12373Falseλ> isPrime 12347Trueλ> isAdditivePrime 12347Trueλ> takeWhile (< 500) $ filter isAdditivePrime primes[2,3,5,7,11,13,23,29,31,41,43,47,61,67,83,89,101,103,113,131,137,139,151,157,173,179,191,193,197,199,211,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]
usingPrimesletp=primesmask(500)println("Additive primes under 500:")pcount=0foriin2:499ifp[i]&&p[sum(digits(i))]pcount+=1print(lpad(i,4),pcount%20==0?"\n":"")endendprintln("\n\n$pcount additive primes found.")end
Erdős 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 48754 additive primes found.
funisPrime(n:Int):Boolean{if(n<=3)returnn>1if(n%2==0||n%3==0)returnfalsevari=5while(i*i<=n){if(n%i==0||n%(i+2)==0)returnfalsei+=6}returntrue}fundigitSum(n:Int):Int{varsum=0varnum=nwhile(num>0){sum+=num%10num/=10}returnsum}funmain(){varadditivePrimes=0for(iin2until500){if(isPrime(i)andisPrime(digitSum(i))){additivePrimes++print("$i ")}}println("\nFound$additivePrimes additive primes less than 500")}
2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151 157 173 179 191 193 197 199 223 227 229 241 263 269 281 283 311 313 317 331 337 353 359 373 379 397 401 409 421 443 449 461 463 467 487 Found 54 additive primes less than 500
#!/bin/ksh# Prime numbers for which the sum of their decimal digits are also primes# # Variables:#integerMAX_n=500# # Functions:## # Function _isprime(n) return 1 for prime, 0 for not prime#function_isprime{typeset_n;integer_n=$1typeset_i;integer_i((_n<2))&&return0for((_i=2;_i*_i<=_n;_i++));do((!(_n%_i)))&&return0donereturn1}# # Function _sumdigits(n) return sum of n's digits#function_sumdigits{typeset_n;_n=$1typeset_i_sum;integer_i_sum=0for((_i=0;_i<${#_n};_i++));do((_sum+=${_n:${_i}:1}))doneecho${_sum}}####### main #######integeridigsumfor((i=2;i<MAX_n;i++));do_isprime${i}&&((!$?))&&continuedigsum=$(_sumdigits${i})_isprime${digsum};(($?))&&printf"%4d "${i}doneprint
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
{defisprime{defisprime.loop{lambda{:n:m:i}{if{>:i:m}thentrueelse{if{={%:n:i}0}thenfalseelse{isprime.loop:n:m{+:i2}}}}}}{lambda{:n}{if{or{=:n2}{=:n3}{=:n5}{=:n7}}thentrueelse{if{or{<:n2}{={%:n2}0}}thenfalseelse{isprime.loop:n{sqrt:n}3}}}}}->isprime{defdigit.sum{defdigit.sum.loop{lambda{:n:sum}{if{>:n0}then{digit.sum.loop{floor{/:n10}}{+:sum{%:n10}}}else:sum}}}{lambda{:n}{digit.sum.loop:n0}}}->digit.sum{S.replace\sbyspacein{S.map{lambda{:i}{if{and{isprime:i}{isprime{digit.sum:i}}}then:ielse}}{S.serie2500}}}->235711232941434761678389101113131137139151157173179191193197199223227229241263269281283311313317331337353359373379397401409421443449461463467487i.e54additiveprimesuntil500.
val isPrime = fn(i) { i == 2 or i > 2 and not any(series(2 .. i ^/ 2, asconly=true), by=fn x:i div x)}val sumDigits = fn i: fold(s2n(string(i)), by=fn{+})writeln "Additive primes less than 500:"var cnt = 0for i in [2] ~ series(3..500, inc=2) { if isPrime(i) and isPrime(sumDigits(i)) { write "{{i:3}} " cnt += 1 if cnt div 10: writeln() }}writeln "\n\n{{cnt}} additive primes found.\n"Additive primes less than 500: 2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151 157 173 179 191 193 197 199 223 227 229 241 263 269 281 283 311 313 317 331 337 353 359 373 379 397 401 409 421 443 449 461 463 467 487 54 additive primes found.
This task usesprimegen from:Extensible_prime_generator#Lua
functionsumdigits(n)localsum=0whilen>0dosum=sum+n%10n=math.floor(n/10)endreturnsumendprimegen:generate(nil,500)aprimes=primegen:filter(function(n)returnprimegen.tbd(sumdigits(n))end)print(table.concat(aprimes," "))print("Count:",#aprimes)
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 487Count: 54
ClearAll[AdditivePrimeQ]AdditivePrimeQ[n_Integer]:=PrimeQ[n]\[And]PrimeQ[Total[IntegerDigits[n]]]Select[Range[500],AdditivePrimeQ]
{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}/* Function that returns a list of digits given a nonnegative integer */decompose(num):=block([digits,remainder],digits:[],whilenum>0do(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(%);
[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
isPrime=function(n)ifn<=3thenreturnn>1ifn%2==0orn%3==0thenreturnfalsei=5whilei^2<=nifn%i==0orn%(i+2)==0thenreturnfalsei+=6endwhilereturntrueendfunctiondigitSum=function(n)sum=0whilen>0sum+=n%10n=floor(n/10)endwhilereturnsumendfunctionadditive=[]foriinrange(2,500)ifisPrime(i)andisPrime(digitSum(i))thenadditive.push(i)endforprint"There are "+additive.len+" additive primes under 500."printadditive
miniscript.exe additive-prime.msThere 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]
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), otherwiseadditive_prime :: num->booladditive_prime n = prime (dsum n) & prime ndsum :: num->numdsum n = n, if n<10 = n mod 10 + dsum (n div 10), otherwiseprime :: num->boolprime n = n>=2 & #[d | d<-[2..entier (sqrt n)]; n mod d=0] = 0
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 487Found 54 additive primes < 500
MODULEAdditivePrimes;FROMInOutIMPORTWriteString,WriteCard,WriteLn;CONSTMax=500;VARN:CARDINAL;Count:CARDINAL;Prime:ARRAY[2..Max]OFBOOLEAN;PROCEDUREDigitSum(n:CARDINAL):CARDINAL;BEGINIFn<10THENRETURNn;ELSERETURN(nMOD10)+DigitSum(nDIV10);END;ENDDigitSum;PROCEDURESieve;VARi,j,max2:CARDINAL;BEGINFORi:=2TOMaxDOPrime[i]:=TRUE;END;FORi:=2TOMaxDIV2DOIFPrime[i]THEN;j:=i*2;WHILEj<=MaxDOPrime[j]:=FALSE;j:=j+i;END;END;END;ENDSieve;BEGINCount:=0;Sieve();FORN:=2TOMaxDOIFPrime[N]ANDPrime[DigitSum(N)]THENWriteCard(N,4);Count:=Count+1;IFCountMOD10=0THENWriteLn();END;END;END;WriteLn();WriteString('There are ');WriteCard(Count,0);WriteString(' additive primes less than ');WriteCard(Max,0);WriteString('.');WriteLn();ENDAdditivePrimes.
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 487There are 54 additive primes less than 500.
MODULEAdditivePrimesEXPORTSMain;IMPORTSIO,Fmt;CONSTMax=500;VARCount:CARDINAL:=0;Prime:ARRAY[2..Max]OFBOOLEAN;PROCEDUREDigitSum(N:CARDINAL):CARDINAL=BEGINIFN<10THENRETURNNELSERETURN(NMOD10)+DigitSum(NDIV10)END;ENDDigitSum;PROCEDURESieve()=VARJ:CARDINAL;BEGINFORI:=2TOMaxDOPrime[I]:=TRUEEND;FORI:=2TOMaxDIV2DOIFPrime[I]THENJ:=I*2;WHILEJ<=MaxDOPrime[J]:=FALSE;INC(J,I)ENDENDEND;ENDSieve;BEGINSieve();FORN:=2TOMaxDOIFPrime[N]ANDPrime[DigitSum(N)]THENSIO.PutText(Fmt.F("%4s",Fmt.Int(N)));INC(Count);IFCountMOD10=0THENSIO.Nl()ENDENDEND;SIO.PutText(Fmt.F("\nThere are %s additive primes less than %s.\n",Fmt.Int(Count),Fmt.Int(Max)));ENDAdditivePrimes.
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 487There are 54 additive primes less than 500.
importmath,strutilsconstN=499# Sieve of Erathostenes.varcomposite:array[2..N,bool]# Initialized to false, ie. prime.fornin2..sqrt(N.toFloat).int:ifnotcomposite[n]:forkincountup(n*n,N,n):composite[k]=truefuncdigitSum(n:Positive):Natural=## Compute sum of digits.varn=n.intwhilen!=0:result+=nmod10n=ndiv10echo"Additive primes less than 500:"varcount=0fornin2..N:ifnotcomposite[n]andnotcomposite[digitSum(n)]:inccountstdout.write($n).align(3)stdout.writeifcountmod10==0:'\n'else:' 'echo()echo"\nNumber of additive primes found: ",count
Additive primes less than 500: 2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151157 173 179 191 193 197 199 223 227 229241 263 269 281 283 311 313 317 331 337353 359 373 379 397 401 409 421 443 449461 463 467 487 Number of additive primes found: 54
The source of Primes.Mod (the RC prime utilities module) is on a separate page on Rosetta Code - see the above link.
MODULEAdditivePrimes;IMPORTOut,Primes;CONSTMax=500;VARCount,n:INTEGER;Prime:ARRAYMax+1OFBOOLEAN;PROCEDUREDigitSum(n:INTEGER):INTEGER;VARresult:INTEGER;BEGINresult:=0;IFn<10THENresult:=nELSEresult:=(nMOD10)+DigitSum(nDIV10)ENDRETURNresultENDDigitSum;BEGINPrimes.sieve(Prime);FORn:=2TOMaxDOIFPrime[n]&Prime[DigitSum(n)]THENOut.Int(n,4);INC(Count);IFCountMOD20=0THENOut.LnENDENDEND;Out.Ln;Out.String("There are ");Out.Int(Count,1);Out.String(" additive primes less than ");Out.Int(Max,1);Out.String(".");Out.LnENDAdditivePrimes.
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 487There are 54 additive primes less than 500.
letrecdigit_sumn=ifn<10thennelsenmod10+digit_sum(n/10)letis_primen=letrectestx=letq=n/xinx>q||x*q<>n&&nmod(x+2)<>0&&test(x+6)inifn<5thennlor1=3elsenland1<>0&&nmod3<>0&&test5letis_additive_primen=is_primen&&is_prime(digit_sumn)let()=Seq.ints0|>Seq.take_while((>)500)|>Seq.filteris_additive_prime|>Seq.iter(Printf.printf" %u")|>print_newline
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
This is a good task for demonstrating several different ways to approach a simple problem.
hasPrimeDigitsum(n)=isprime(sumdigits(n)); \\ see A028834 in the OEISv1 = select(isprime, select(hasPrimeDigitsum, [1..499]));v2 = select(hasPrimeDigitsum, select(isprime, [1..499]));v3 = select(hasPrimeDigitsum, primes([1, 499]));s=0; forprime(p=2,499, if(hasPrimeDigitsum(p), s++)); s;[#v1, #v2, #v3, s]
%1 = [54, 54, 54, 54]
checking isPrime(sum of digits) before testimg isprime(num) improves speed.
Tried to speed up calculation of sum of digits.
programAdditivePrimes;{$IFDEF FPC}{$MODE DELPHI}{$CODEALIGN proc=16}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF}{$DEFINE DO_OUTPUT}usessysutils;constRANGE=500;// 1000*1000;//MAX_OFFSET=0;// 1000*1000*1000;//typetNum=array[0..15]ofbyte;tNumSum=recorddgtNum,dgtSum:tNum;dgtLen,num:Uint32;end;tpNumSum=^tNumSum;functionisPrime(n:Uint32):boolean;constwheeldiff:array[0..7]ofUint32=(+6,+4,+2,+4,+2,+4,+6,+2);varp:NativeUInt;flipflop:Int32;beginifn<64thenEXIT(nin[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61])elsebeginIF(nAND1=0)OR(nmod3=0)OR(nmod5=0)thenEXIT(false);result:=true;p:=1;flipflop:=6;whileresultdoBeginp:=p+wheeldiff[flipflop];ifp*p>nthenBREAK;result:=nmodp<>0;flipflop:=flipflop-1;ifflipflop<0thenflipflop:=7;endendend;procedureIncNum(varNumSum:tNumSum;delta:Uint32);constBASE=10;varcarry,dg:Uint32;le:Int32;Beginifdelta=0thenEXIT;le:=0;withNumSumdobeginnum:=num+delta;repeatcarry:=deltadivBASE;delta:=delta-BASE*carry;dg:=dgtNum[le]+delta;IFdg>=BASEthenBegindg:=dg-BASE;inc(carry);end;dgtNum[le]:=dg;inc(le);delta:=carry;untilcarry=0;ifdgtLen<lethendgtLen:=le;// correct sum of digits // le is >= 1delta:=dgtSum[le];repeatdec(le);delta:=delta+dgtNum[le];dgtSum[le]:=delta;untille=0;end;end;varNumSum:tNumSum;s:AnsiString;i,k,cnt,Nr:NativeUInt;ColWidth,MAXCOLUMNS,NextRowCnt:NativeUInt;BEGINColWidth:=Trunc(ln(MAX_OFFSET+RANGE)/ln(10))+2;MAXCOLUMNS:=80;NextRowCnt:=MAXCOLUMNSDIVColWidth;fillchar(NumSum,SizeOf(NumSum),#0);NumSum.dgtLen:=1;IncNum(NumSum,MAX_OFFSET);setlength(s,ColWidth);fillchar(s[1],ColWidth,' ');// init stringwithNumSumdoBeginFori:=dgtLen-1downto0dos[ColWidth-i]:=AnsiChar(dgtNum[i]+48);// reset digits lenght to get the max changed digits since last update of stringdgtLen:=0;end;cnt:=0;Nr:=NextRowCnt;Fori:=0toRANGEdowithNumSumdobeginifisPrime(dgtSum[0])thenifisPrime(num)thenBegincnt:=cnt+1;dec(Nr);// correct changed digits in string sFork:=dgtLen-1downto0dos[ColWidth-k]:=AnsiChar(dgtNum[k]+48);dgtLen:=0;{$IFDEF DO_OUTPUT}write(s);ifNr=0thenbeginwriteln;Nr:=NextRowCnt;end;{$ENDIF}end;IncNum(NumSum,1);end;ifNr<>NextRowCntthenwrite(#10);writeln(cnt,' additive primes found.');END.
TIO.RUN 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 48754 additive primes found.//OFFSET : 1000*1000*1000, RANGE = 1000*1000 no output18103 additive primes found.Real time: 1.951 s User time: 1.902 s Sys. time: 0.038 s CPU share: 99.46 %
PascalABC.NET 3.10.3.3614
##usesSchool;//поиск аддитивных простых чиселvarAdditivePrimes:=Primes(500).Where(n->n.Digits.Sum.IsPrime).ToArray;Print('Additive Primes:');AdditivePrimes.Println;Println('Additive Primes Count:',AdditivePrimes.Count);
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 487Additive Primes Count: 54
usestrict;usewarnings;usentheory'is_prime';useList::Util<summax>;subpp{my$format=('%'.(my$cw=1+lengthmax@_).'d')x@_;my$width=".{@{[$cw * int 60/$cw]}}";(sprintf($format,@_))=~s/($width)/$1\n/gr;}my($limit,@ap)=500;is_prime($_)andis_prime(sum(split'',$_))andpush@ap,$_for1..$limit;print@ap." additive primes < $limit:\n".pp(@ap);
54 additive primes < 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
withjavascript_semanticsfunctionadditive(stringp)returnis_prime(sum(sq_sub(p,'0')))endfunctionsequenceres=filter(apply(get_primes_le(500),sprint),additive)printf(1,"%d additive primes found: %s\n",{length(res),join(shorten(res,"",6))})
54 additive primes found: 2 3 5 7 11 23 ... 443 449 461 463 467 487
/# Rosetta Code problem: http://rosettacode.org/wiki/Additive_primesby Galileo, 05/2022 #/include ..\Utilitys.pmtdef isprime dup 1 <= if drop false else dup 2 == not if ( dup sqrt 2 swap ) for over swap mod not if drop false exitfor endif endfor endif endif false == notenddefdef digitsum 0 swap dup 0 > while dup 10 mod rot + swap 10 / int dup 0 > endwhile dropenddef0 500 for dup isprime over digitsum isprime and if print " " print 1 + else drop endifendfor"Additive primes found: " print print
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=== Press any key to exit ===
main => PCount = 0, foreach (I in 2..499) if prime(I) && prime(sum_digits(I)) then PCount := PCount + 1, printf("%4d ", I) end end, printf("\n\n%d additive primes found.\n", PCount).sum_digits(N) = S => S = sum([ord(C)-ord('0') : C in to_string(N)]).2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151 157 173 179 191 193 197 199 223 227 229 241 263 269 281 283 311 313 317 331 337 353 359 373 379 397 401 409 421 443 449 461 463 467 487 54 additive primes found.
(de prime? (N) (let D 0 (or (= N 2) (and (> N 1) (bit? 1 N) (for (D 3 T (+ D 2)) (T (> D (sqrt N)) T) (T (=0 (% N D)) NIL) ) ) ) ) )(de additive (N) (and (prime? N) (prime? (sum format (chop N))) ) )(let C 0 (for (N 0 (> 500 N) (inc N)) (when (additive N) (printsp N) (inc 'C) ) ) (prinl) (prinl "Total count: " C) )
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 Total count: 54
C :z=2 :c=0 :max=500*numberC :n=zU :*digsum C :n=sU :*primeJ (p=0):*nextC :n=zU :*primeJ (p=0):*nextT :#zC :c=c+1*nextC :z=z+1J (z<max):*numberT :There are #c additive primes below #maxE :*primeC :p=1E (n<4):C :p=0E (n=2*(n/2)):C :i=3 :m=n/2*ptestE (n=i*(n/i)):C :i=i+2J (i<=m):*ptestC :p=1E :*digsumC :s=0 :i=n*digitC :j=i/10 :s=s+(i-j*10) :i=jJ (i>0):*digitE :
235711232941434761678389101113131137139151157173179191193197199223227229241263269281283311313317331337353359373379397401409421443449461463467487There are 54 additive primes below 500
additive_primes: procedure options (main); %replace search_limit by 500, true by '1'b, false by '0'b; dcl (i, count) fixed bin; put skip edit('Searching up to ', search_limit, ' for additive primes') (a,f(3),a); put skip; count = 0; do i = 2 to search_limit; if isprime(i) then do; if isprime(sumdigits(i)) then do; put edit(i) (f(5)); count = count + 1; if mod(count,8) = 0 then put skip; end; end; end; put skip edit(count, ' were found') (f(3), a);/* return true if n is prime */isprime: proc(n) returns (bit(1)); dcl (n, i, limit) fixed bin; if n < 2 then return (false); if mod(n, 2) = 0 then return (n = 2); limit = floor(sqrt(n)); i = 3; do while ((i <= limit) & (mod(n, i) ^= 0)); i = i + 2; end; return (i > limit); end isprime;/* return the sum of the digits of n */sumdigits: proc(n) returns (fixed bin); dcl (n, nn, sum) fixed bin; /* use copy, since n is passed by reference */ nn = n; sum = 0; do while (nn > 0); sum = sum + mod(nn, 10); nn = nn / 10; end; return (sum);end sumdigits;end additive_primes;Searching up to 500 for 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 54 were found
localint=require"int"localfmt=require"fmt"print("Additive primes less than 500:")localprimes=int.primes(499)localcount=0forprimesaspdoifint.isprime(int.digstat(p)[2])docount+=1fmt.write("%3d ",p)ifcount%10==0thenprint()endendendprint($"\n\n{count} additive primes found.")
Additive primes less than 500: 2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151 157 173 179 191 193 197 199 223 227 229 241 263 269 281 283 311 313 317 331 337 353 359 373 379 397 401 409 421 443 449 461 463 467 487 54 additive primes found.
... under CP/M (or an emulator)
Should work with many PL/I implementations.
The PL/I include file "pg.inc" can be found on thePolyglot: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.
/* FIND ADDITIVE PRIMES - PRIMES WHOSE DIGIT SUM IS ALSO PRIME */additive_primes_100H: procedure options (main);/* PROGRAM-SPECIFIC %REPLACE STATEMENTS MUST APPEAR BEFORE THE %INCLUDE AS *//* E.G. THE CP/M PL/I COMPILER DOESN'T LIKE THEM TO FOLLOW PROCEDURES */ /* PL/I */ %replace dclsieve by 500; /* PL/M */ /* DECLARE DCLSIEVE LITERALLY '501'; /* *//* PL/I DEFINITIONS */%include 'pg.inc';/* PL/M DEFINITIONS: CP/M BDOS SYSTEM CALL AND CONSOLE I/O ROUTINES, ETC. */ /* DECLARE BINARY LITERALLY 'ADDRESS', CHARACTER LITERALLY 'BYTE'; DECLARE FIXED LITERALLY ' ', BIT LITERALLY 'BYTE'; DECLARE STATIC LITERALLY ' ', RETURNS LITERALLY ' '; DECLARE FALSE LITERALLY '0', TRUE LITERALLY '1'; DECLARE HBOUND LITERALLY 'LAST', SADDR LITERALLY '.'; BDOSF: PROCEDURE( FN, ARG )BYTE; DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END; BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END; PRCHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END; PRSTRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END; PRNL: PROCEDURE; CALL PRCHAR( 0DH ); CALL PRCHAR( 0AH ); END; PRNUMBER: PROCEDURE( N ); DECLARE N ADDRESS; DECLARE V ADDRESS, N$STR( 6 ) BYTE, W BYTE; N$STR( W := LAST( N$STR ) ) = '$'; N$STR( W := W - 1 ) = '0' + ( ( V := N ) MOD 10 ); DO WHILE( ( V := V / 10 ) > 0 ); N$STR( W := W - 1 ) = '0' + ( V MOD 10 ); END; CALL BDOS( 9, .N$STR( W ) ); END PRNUMBER; MODF: PROCEDURE( A, B )ADDRESS; DECLARE ( A, B ) ADDRESS; RETURN A MOD B; END MODF;/* END LANGUAGE DEFINITIONS */ /* TASK */ /* PRIME ELEMENTS ARE 0, 1, ... 500 IN PL/M AND 1, 2, ... 500 IN PL/I */ /* ELEMENT 0 IN PL/M IS IS UNUSED */ DECLARE PRIME( DCLSIEVE ) BIT; DECLARE ( MAXPRIME, MAXROOT, ACOUNT, I, J, DSUM, V ) FIXED BINARY; /* SIEVE THE PRIMES UP TO MAX PRIME */ PRIME( 1 ) = FALSE; PRIME( 2 ) = TRUE; MAXPRIME = HBOUND( PRIME , 1 ); MAXROOT = 1; /* FIND THE ROOT OF MAXPRIME TO AVOID 16-BIT OVERFLOW */ DO WHILE( MAXROOT * MAXROOT < MAXPRIME ); MAXROOT = MAXROOT + 1; END; DO I = 3 TO MAXPRIME BY 2; PRIME( I ) = TRUE; END; DO I = 4 TO MAXPRIME BY 2; PRIME( I ) = FALSE; END; DO I = 3 TO MAXROOT BY 2; IF PRIME( I ) THEN DO; DO J = I * I TO MAXPRIME BY I; PRIME( J ) = FALSE; END; END; END; /* FIND THE PRIMES THAT ARE ADDITIVE PRIMES */ ACOUNT = 0; DO I = 1 TO MAXPRIME; IF PRIME( I ) THEN DO; V = I; DSUM = 0; DO WHILE( V > 0 ); DSUM = DSUM + MODF( V, 10 ); V = V / 10; END; IF PRIME( DSUM ) THEN DO; CALL PRCHAR( ' ' ); IF I < 10 THEN CALL PRCHAR( ' ' ); IF I < 100 THEN CALL PRCHAR( ' ' ); CALL PRNUMBER( I ); ACOUNT = ACOUNT + 1; IF MODF( ACOUNT, 12 ) = 0 THEN CALL PRNL; END; END; END; CALL PRNL; CALL PRSTRING( SADDR( 'FOUND $' ) ); CALL PRNUMBER( ACOUNT ); CALL PRSTRING( SADDR( ' ADDITIVE PRIMES BELOW $' ) ); CALL PRNUMBER( MAXPRIME ); CALL PRNL;EOF: end additive_primes_100H;
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 487FOUND 54 ADDITIVE PRIMES BELOW 500
IntList primes = new IntList();void setup() { sieve(500); int count = 0; for (int i = 2; i < 500; i++) { if (primes.hasValue(i) && primes.hasValue(sumDigits(i))) { print(i + " "); count++; } } println(); print("Number of additive primes less than 500: " + count);}int sumDigits(int n) { int sum = 0; for (int i = 0; i <= floor(log(n) / log(10)); i++) { sum += floor(n / pow(10, i)) % 10; } return sum;}void sieve(int max) { for (int i = 2; i <= max; i++) { primes.append(i); } for (int i = 0; i < primes.size(); i++) { for (int j = i + 1; j < primes.size(); j++) { if (primes.get(j) % primes.get(i) == 0) { primes.remove(j); j--; } } }}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 Number of additive primes less than 500: 54
#MAX=500GlobalDimP.b(#MAX):FillMemory(@P(),#MAX,1,#PB_Byte)IfOpenConsole()=0:End1:EndIfForn=2ToSqr(#MAX)+1:IfP(n):m=n*n:Whilem<=#MAX:P(m)=0:m+n:Wend:EndIf:NextProcedure.iqsum(v.i)Whilev:qs+v%10:v/10:WendProcedureReturnqsEndProcedureFori=2To#MAXIfP(i)AndP(qsum(i)):c+1:Print(RSet(Str(i),5)):Ifc%10=0:PrintN(""):EndIf:EndIfNextPrintN(~"\n\n"+Str(c)+" additive primes below 500.")Input()
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 48754 additive primes below 500.
defis_prime(n:int)->bool:ifn<=3:returnn>1ifn%2==0orn%3==0:returnFalsei=5whilei**2<=n:ifn%i==0orn%(i+2)==0:returnFalsei+=6returnTruedefdigit_sum(n:int)->int:sum=0whilen>0:sum+=n%10n//=10returnsumdefmain()->None:additive_primes=0foriinrange(2,500):ifis_prime(i)andis_prime(digit_sum(i)):additive_primes+=1print(i,end=" ")print(f"\nFound{additive_primes} additive primes less than 500")if__name__=="__main__":main()
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
eratosthenes andisprime are defined atSieve of Eratosthenes#Quackery.
digitsum is defined atSum digits of an integer#Quackery.
500 eratosthenes [] 500 times [ i^ isprime if [ i^ 10 digitsum isprime if [ i^ join ] ] ] dup echo cr cr size echo say " additive primes found."
[ 2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151 157 173 179 191 193 197 199 223 227 229 241 263 269 281 283 311 313 317 331 337 353 359 373 379 397 401 409 421 443 449 461 463 467 487 ]54 additive primes found.
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:500v<-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])
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
#langracket(requiremath/number-theory)(define(sum-of-digitsn(σ0))(if(zero?n)σ(let-values(((qr)(quotient/remaindern10)))(sum-of-digitsq(+σr)))))(define(additive-prime?n)(and(prime?n)(prime?(sum-of-digitsn))))(defineadditive-primes<500(filteradditive-prime?(range1500)))(printf"There are ~a additive primes < 500~%"(lengthadditive-primes<500))(printf"They are: ~a~%"additive-primes<500)
There are 54 additive primes < 500They are: (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)
unitsubMAIN ($limit =500);say"{+$_} additive primes < $limit:\n{$_».fmt("%" ~ $limit.chars ~ "d").batch(10).join("\n")}",with ^$limit .grep: { .is-prime && .comb.sum.is-prime }
54 additive primes < 500: 2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151157 173 179 191 193 197 199 223 227 229241 263 269 281 283 311 313 317 331 337353 359 373 379 397 401 409 421 443 449461 463 467 487
Rebol[title:"Rosetta code: Additive primes"file:%Additive_primes.r3url:https://rosettacode.org/wiki/Additive_primesnote:"Based on Red language solution"]primes:function[n[integer!]][;; See: https://rosettacode.org/wiki/Sieve_of_Eratosthenes#Rebolpokeprim:makebitset!n1truer:2while[r*r<=n][repeatqn/r-1[pokeprimq+1*rtrue]until[notpickprimr:r+1]]collect[repeatin[unlessprim/:i[keepi]]]];; Compute the digit sum (cross-sum) of an integer ncross-sum:function[n][out:0;; accumulator for sum of digitsforeachmformn[;; iterate over the characters of n's string formout:out-48+m;; convert char to integer, add to out]out];; Return all additive primes <= n:;; A prime p is "additive" if its digit-sum is also prime.additive-primes:function[n][collect[foreachpps:primesn[;; generate primes up to n and iterate over themiffindpscross-sump[;; check if digit-sum of p is itself in the prime setkeepp;; keep p if digit-sum is prime]]]];; Generate additive primes up to 500result:additive-primes500;; Format nicely by rows of 10 (with newlines)print[length?result"additive primes < 500:"]forallresult[prinpadresult/1-4ifzero?((index? result)%10)[print""]]print""
54 additive primes < 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
cross-sum:function[n][out:0foreachmformn[out:out+to-integerto-stringm]]additive-primes:function[n][collect[foreachpps:primesn[iffindpscross-sump[keepp]]]]length?probenew-line/skipadditive-primes500true10[235711232941434761678389101113131137139151157173179191193197199223227229241263269281283311313317331337353359373379397401409421443449461463467487]==54
Usesprimes defined inhttps://rosettacode.org/wiki/Sieve_of_Eratosthenes#Red.
/*REXX program counts/displays the number of additive primes less than N. */ParseArgncols./*get optional number of primes To find*/Ifn==''|n==','Thenn=500/*Not specified? Then assume default.*/Ifcols==''|cols==','Thencols=10/* ' ' ' ' ' */callgenPn/*generate all primes under N. */w=5/*width of a number in any column. */title='additive primes that are < 'commas(n)Ifcols>0ThenSay' index ¦'center(title,cols*(w+1)+1)Ifcols>0ThenSay'-------+'center('',cols*(w+1)+1,'-')found=0ol=''/*a list of additive primes (so far). */idx=1Doj=1By1p=p.j/*obtain the Jth prime. */Ifp>nThenLeave/* no more needed */_=sumDigs(p)If!._ThenDofound=found+1/*bump the count of additive primes. */c=commas(p)/*maybe add commas To the number. */ol=olright(c,max(w,length(c)))/*add additive prime--?list,allow big# */Ifwords(ol)=10ThenDo/* a line is complete */Saycenter(idx,7)'¦'substr(ol,2)/*display what we have so far (cols). */ol=''/* prepare for next line */idx=idx+10EndEndEnd/*j*/Ifol\==''ThenSaycenter(idx,7)'¦'substr(ol,2)/*possible display residual output. */Ifcols>0ThenSay'--------'center('',cols*(w+1)+1,'-')SaySay'found 'commas(found)titleExit0/*stick a fork in it, we're all done. *//*--------------------------------------------------------------------------------*/commas:ParseArg?;Dojc=length(?)-3To1by-3;?=insert(',',?,jc);End;Return?sumDigs:ParseArgx1s2;Dok=2Forlength(x)-1;s=s+substr(x,k,1);End;Returns/*--------------------------------------------------------------------------------*/genP:ParseArgnpl=23571113!.=0Donp=1By1Whilepl<>''ParseVarplpplp.np=psq.np=p*p!.p=1Endnp=np-1Doj=p.np+2by2Whilej<nParseVarj''-1_/*obtain the last digit of the J var.*/If_==5ThenIterateIfj//3==0ThenIterateIfj//7==0ThenIterateIfj//11==0ThenIterateDok=6By1Whilesq.k<=j/*divide J by other primes <=sqrt(j) */Ifj//p.k==0ThenIteratej/* not prime - try next */End/*k*/np=np+1/*bump prime count; assign prime & flag*/p.np=jsq.np=j*j!.j=1End/*j*/Return
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
Some timings for this version, output suppressed, Regina
found 89 additive primes that are < 1,0000.002000 secondsfound 590 additive primes that are < 10,0000.031000 secondsfound 3,883 additive primes that are < 100,0000.542000 secondsfound 30,123 additive primes that are < 1,000,00016.753000 seconds
Modules:How to use
Modules:Source code
Function Additives() collects all additive primes up to the given parameter, and returns the number of primes found. See module Sequences.
--23Aug2025includeSettingsay'ADDITIVE PRIMES'sayversionsayargnnumericdigits16ifn=''thenn=500show=(n>0);n=Abs(n)a=Additives(n)ifshowthendodoi=1toacallCharout,Right(addi.i,8)' 'ifi//10=0thensayendsayendsaya'additive primes found below'nsayTime('e')/1'seconds'exitincludeMath
ADDITIVE PRIMESREXX-Regina_3.9.6(MT) 5.00 29 Apr 20242 3 5 7 11 23 29 41 43 4761 67 83 89 101 113 131 137 139 151157 173 179 191 193 197 199 223 227 229241 263 269 281 283 311 313 317 331 337353 359 373 379 397 401 409 421 443 449461 463 467 48754 additive primes found below 5000.002000 seconds
And some timings for this version, output suppressed, Regina.
89 additive primes found below 10000.001000 seconds590 additive primes found below 100000.010000 seconds3883 additive primes found below 1000000.086000 seconds30123 additive primes found below 10000000.979000 seconds246982 additive primes found below 1000000016.194000 seconds
load "stdlib.ring"see "working..." + nlsee "Additive primes are:" + nlrow = 0limit = 500for n = 1 to limit num = 0 if isprime(n) strn = string(n) for m = 1 to len(strn) num = num + number(strn[m]) next if isprime(num) row = row + 1 see "" + n + " " if row%10 = 0 see nl ok ok oknextsee nl + "found " + row + " additive primes." + nlsee "done..." + nl
working...Additive primes are: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.done...
≪ →STR 0 1 3 PICK SIZEFOR j OVER j DUP SUB STR→ +NEXT NIP≫ '∑DIGITS' STO≪ { } 1DO NEXTPRIMEIF DUP∑DIGITS ISPRIME?THEN SWAP OVER + SWAPENDUNTIL DUP 500 ≥END DROP DUP SIZE≫ 'TASK' STO
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: 54require"prime"additive_primes=Prime.lazy.select{|prime|prime.digits.sum.prime?}N=500res=additive_primes.take_while{|n|n<N}.to_aputsres.join(" ")puts"\n#{res.size} additive primes below#{N}."
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 48754 additive primes below 500.
fnmain(){letlimit=500;letcolumn_w=limit.to_string().len()+1;letmutpms=Vec::with_capacity(limit/2-limit/3/2-limit/5/3/2+1);letmutcount=0;foruin(2..3).chain((3..limit).step_by(2)){ifpms.iter().take_while(|&&p|p*p<=u).all(|&p|u%p!=0){pms.push(u);letdgs=std::iter::successors(Some(u),|&n|(n>9).then(||n/10)).map(|n|n%10);ifpms.binary_search(&dgs.sum()).is_ok(){print!("{}{u:column_w$}",ifcount%10==0{"\n"}else{""});count+=1;}}}println!("\n---\nFound {count} additive primes less than {limit}");}
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
primal implements the sieve of Eratosthenes with optimizations (10+ times faster for large limits)
// [dependencies]// primal = "0.3.0"fnsum_digits(u:usize)->usize{std::iter::successors(Some(u),|&n|(n>9).then(||n/10)).fold(0,|s,n|s+n%10)}fnmain(){letlimit=500;letcolumn_w=limit.to_string().len()+1;letsieve_primes=primal::Sieve::new(limit);letcount=sieve_primes.primes_from(2).filter(|&p|p<limit&&sieve_primes.is_prime(sum_digits(p))).zip(["\n"].iter().chain(&["";9]).cycle()).inspect(|(u,sn)|print!("{sn}{u:column_w$}")).count();println!("\n---\nFound {count} additive primes less than {limit}");}
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
limit = 500additivePrimes = list(filter(lambda x: x > 0, list(map(lambda x: int(x) if sum([int(digit) for digit in x]) in Primes() else 0, list(map(str,list(primes(1,limit))))))))print(f"{additivePrimes}\nFound {len(additivePrimes)} additive primes less than {limit}")[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
$constanttrue=0FFFFH$constantfalse=0$constantlimit=500functionsum.of.digits(n=integer)=integervari,sum=integervars=stringvarch=chars=str$(n)sum=0fori=2tolen(s)ch=mid(s,i,1)sum=sum+(ch-'0')nextiend=sumfunctionmod(n,m=integer)=integerend=n-(n/m)*mcommentbuildatableofprimenumbersusingtheclassicsieveofErathosthenesenddimintegerprime(limit)vari,j,count=integerprime(1)=falsefori=2tolimitprime(i)=truenextirem-strikeoutmultiplesofeachprimefoundfori=2tosqr(limit)ifprime(i)thenbeginforj=i+itolimitstepiprime(j)=falsenextjendnextirem-usethetableforthesearchprint"Searching up to";limit;" for additive primes"count=0fori=2tolimitifprime(i)thenifprime(sum.of.digits(i))thenbeginprintusing"### ";i;count=count+1ifmod(count,10)=0thenprintendnextiprintprintcount;" were found"end
Searching up to 500 for additive primes 2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151157 173 179 191 193 197 199 223 227 229241 263 269 281 283 311 313 317 331 337 353 359 373 379 397 401 409 421 443 449 461 463 467 487 54 were found
defisPrime(n:Int):Boolean={@annotation.tailrecdefcheckDivisor(d:Int):Boolean={if(d*d>n)trueelseif(n%d==0)falseelsecheckDivisor(d+2)}if(n<2)falseelseif(n==2||n==3)trueelseif(n%2==0||n%3==0)falseelsecheckDivisor(5)}privatedefdigitSum(n:Int):Int=n.toString.map(_-'0').sumprivatedefadditivePrime(n:Int):Boolean=isPrime(n)&&isPrime(digitSum(n))privatedeftestAdditivePrime(max:Int):Unit={valresult=(2tomax).filter(additivePrime)println(result.mkString(", "))println(s"Found${result.length} additive primes less than 500.")}@maindefmain():Unit=testAdditivePrime(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, 487Found 54 additive primes less than 500.
$ include "seed7_05.s7i";const func boolean: isPrime (in integer: number) is func result var boolean: prime is FALSE; local var integer: upTo is 0; var integer: testNum is 3; begin if number = 2 then prime := TRUE; elsif odd(number) and number > 2 then upTo := sqrt(number); while number rem testNum <> 0 and testNum <= upTo do testNum +:= 2; end while; prime := testNum > upTo; end if; end func;const func integer: digitSum (in var integer: number) is func result var integer: sum is 0; begin while number > 0 do sum +:= number rem 10; number := number div 10; end while; end func;const proc: main is func local var integer: n is 0; var integer: count is 0; begin for n range 2 to 499 do if isPrime(n) and isPrime(digitSum(n)) then write(n lpad 3 <& " "); incr(count); if count rem 9 = 0 then writeln; end if; end if; end for; writeln("\nFound " <& count <& " additive primes < 500."); end func;2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137139 151 157 173 179 191 193 197 199223 227 229 241 263 269 281 283 311313 317 331 337 353 359 373 379 397401 409 421 443 449 461 463 467 487Found 54 additive primes < 500.
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;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 487There are 54 additive primes less than 500.
funcadditive_primes(upto,base=10){upto.primes.grep{.sumdigits(base).is_prime}}additive_primes(500).each_slice(10,{|*a|a.map{'%3s'%_}.join(' ').say})
2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151157 173 179 191 193 197 199 223 227 229241 263 269 281 283 311 313 317 331 337353 359 373 379 397 401 409 421 443 449461 463 467 487
importFoundationfuncisPrime(_n:Int)->Bool{ifn<2{returnfalse}ifn%2==0{returnn==2}ifn%3==0{returnn==3}varp=5whilep*p<=n{ifn%p==0{returnfalse}p+=2ifn%p==0{returnfalse}p+=4}returntrue}funcdigitSum(_num:Int)->Int{varsum=0varn=numwhilen>0{sum+=n%10n/=10}returnsum}letlimit=500print("Additive primes less than\(limit):")varcount=0fornin1..<limit{ifisPrime(digitSum(n))&&isPrime(n){count+=1print(String(format:"%3d",n),terminator:count%10==0?"\n":" ")}}print("\n\(count) additive primes found.")
Additive primes less than 500: 2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151157 173 179 191 193 197 199 223 227 229241 263 269 281 283 311 313 317 331 337353 359 373 379 397 401 409 421 443 449461 463 467 487 54 additive primes found.
INTEGER PROC FNMathGetSquareRootI( INTEGER xI ) INTEGER squareRootI = 0 IF ( xI > 0 ) WHILE( ( squareRootI * squareRootI ) <= xI ) squareRootI = squareRootI + 1 ENDWHILE squareRootI = squareRootI - 1 ENDIF RETURN( squareRootI )END//INTEGER PROC FNMathCheckIntegerIsPrimeB( INTEGER nI ) INTEGER I = 0 INTEGER primeB = FALSE INTEGER stopB = FALSE INTEGER restI = 0 INTEGER limitI = 0 primeB = FALSE IF ( nI <= 0 ) RETURN( FALSE ) ENDIF IF ( nI == 1 ) RETURN( FALSE ) ENDIF IF ( nI == 2 ) RETURN( TRUE ) ENDIF IF ( nI == 3 ) RETURN( TRUE ) ENDIF IF ( nI MOD 2 == 0 ) RETURN( FALSE ) ENDIF IF ( ( nI MOD 6 ) <> 1 ) AND ( ( nI MOD 6 ) <> 5 ) RETURN( FALSE ) ENDIF limitI = FNMathGetSquareRootI( nI ) I = 3 REPEAT restI = ( nI MOD I ) IF ( restI == 0 ) primeB = FALSE stopB = TRUE ENDIF IF ( I > limitI ) primeB = TRUE stopB = TRUE ENDIF I = I + 2 UNTIL ( stopB ) RETURN( primeB )END//INTEGER PROC FNMathCheckIntegerDigitSumI( INTEGER J ) STRING s[255] = Str( J ) STRING cS[255] = "" INTEGER minI = 1 INTEGER maxI = Length( s ) INTEGER I = 0 INTEGER K = 0 FOR I = minI TO maxI cS = s[ I ] K = K + Val( cS ) ENDFOR RETURN( K )END//INTEGER PROC FNMathCheckIntegerDigitSumIsPrimeB( INTEGER I ) INTEGER J = FNMathCheckIntegerDigitSumI( I ) INTEGER B = FNMathCheckIntegerIsPrimeB( J ) RETURN( B )END//INTEGER PROC FNMathGetPrimeAdditiveAllToBufferB( INTEGER maxI, INTEGER bufferI ) INTEGER B = FALSE INTEGER B1 = FALSE INTEGER B2 = FALSE INTEGER B3 = FALSE INTEGER minI = 2 INTEGER I = 0 FOR I = minI TO maxI B1 = FNMathCheckIntegerIsPrimeB( I ) B2 = FNMathCheckIntegerDigitSumIsPrimeB( I ) B3 = B1 AND B2 IF ( B3 ) PushPosition() PushBlock() GotoBufferId( bufferI ) AddLine( Str( I ) ) PopBlock() PopPosition() ENDIF ENDFOR B = TRUE RETURN( B )END//PROC Main() STRING s1[255] = "500" // change this INTEGER bufferI = 0 PushPosition() bufferI = CreateTempBuffer() PopPosition() IF ( NOT ( Ask( " = ", s1, _EDIT_HISTORY_ ) ) AND ( Length( s1 ) > 0 ) ) RETURN() ENDIF Message( FNMathGetPrimeAdditiveAllToBufferB( Val( s1 ), bufferI ) ) // gives e.g. TRUE GotoBufferId( bufferI )END
235711232941434761678389101113131137139151157173179191193197199223227229241263269281283311313317331337353359373379397401409421443449461463467487
functionisPrime(n:number):boolean{if(n<2)returnfalse;if(n<4)returntrue;if(n%2==0||n%3==0)returnfalse;for(leti=5;i<=n**0.5;i+=6){if(n%i==0||n%(i+2)==0)returnfalse;}returntrue;}functionsumDigits(x:number):number{letsum=0;while(x>0){sum=sum+(x%10);x=Math.floor(x/10);}returnsum;}constadditivePrimes:number[]=[];for(leti=2;i<10**7;i++){if(isPrime(i)&&isPrime(sumDigits(i))){additivePrimes.push(i);}}console.log(additivePrimes);console.log(`Found${additivePrimes.length} values`);
[ 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 values
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 endifnextend_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 loopreturn (1) _digSum param (1) local (1) b@ = 0 do while a@ b@ = b@ + (a@ % 10) a@ = a@ / 10 loopreturn (b@)
Prime Digit Sum2 23 35 57 711 223 529 1141 543 747 1161 767 1383 1189 17101 2113 5131 5137 11139 13151 7157 13173 11179 17191 11193 13197 17199 19223 7227 11229 13241 7263 11269 17281 11283 13311 5313 7317 11331 7337 13353 11359 17373 13379 19397 19401 5409 13421 7443 11449 17461 11463 13467 17487 190 OK, 0:176
[] # 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.⧻.
[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
Version #2
Prime ← =₁⧻°/×⊸⧻▽⊸≡(×Prime/+⊥₁₀⟜Prime) ↘2⇡500
1. The Prime Test Function
Prime ← =₁⧻°/×
This helper function determines if a number is prime using prime factorization:
°/× (un product): This is the inverse of product reduction. In Uiua, inverting a product performs prime factorization. For example, 20 becomes {2, 2, 5}.⧻ (length): Counts how many factors were found.=₁ (equals 1): A number is prime if and only if it has exactly one prime factor (itself).
2. Generating the Range
↘2⇡500
⇡500 (range): Generates a list of integers from 0 to 499.↘2 (drop 2): Removes the first two elements (0 and 1) because they are not prime by definition. The list now contains numbers from 2 to 499.
3. The Additive Prime Logic
≡(×Prime/+⊥₁₀⟜Prime)
This section acts as a filter mask applied to each number (≡ for rows/each) in the list:⟜Prime (on): Applies the Prime function to the number but keeps the original number at the top of the stack for the next step.⊥₁₀ (base 10): Decomposes the number into its individual decimal digits./+ (sum): Adds the digits together.Prime: Checks if this sum of digits is also a prime number.× (multiply): Multiplies the two boolean results (1 for true, 0 for false). In Uiua, multiplying booleans acts as a logical AND. The result is 1 only if both the number and its digit sum are prime.
4. Filtering and Output
⊸⧻▽⊸
⊸ (by): This is a modifier that keeps the original range (2–499) on the stack to be used by the next function.▽ (keep): This filters the list, keeping only the numbers where the previous logic returned 1.⊸⧻ (by length): Calculates the length of the final list (the count of additive primes) while keeping the list itself on the stack to display both.Summary of the output: The program first displays the list of 54 additive primes found, then displays the total count 54 at the end.
fn is_prime(n int) bool { if n < 2 { return false } else if n%2 == 0 { return n == 2 } else if n%3 == 0 { return n == 3 } else { mut d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true }} fn sum_digits(nn int) int { mut n := nn mut sum := 0 for n > 0 { sum += n % 10 n /= 10 } return sum} fn main() { println("Additive primes less than 500:") mut i := 2 mut count := 0 for { if is_prime(i) && is_prime(sum_digits(i)) { count++ print("${i:3} ") if count%10 == 0 { println('') } } if i > 2 { i += 2 } else { i++ } if i > 499 { break } } println("\n\n$count additive primes found.")}Additive primes less than 500: 2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151 157 173 179 191 193 197 199 223 227 229 241 263 269 281 283 311 313 317 331 337 353 359 373 379 397 401 409 421 443 449 461 463 467 487 54 additive primes found.
10 M=49920 :1)=130 P=240 :P)=050 P=P+160 #=M>P*4070 P=280 C=P*290 :C)=1110 C=C+P120 #=M>C*90130 P=P+1140 #=M/2>P*80150 P=2160 N=0170 #=:P)*290180 S=0190 K=P200 K=K/10210 S=S+%220 #=0<K*200230 #=:S)*290240 ?=P250 $=9260 N=N+1270 #=N/10*0+%=0=0*290280 ?=""290 P=P+1300 #=M>P*170310 ?=""320 ?="There are ";330 ?=N340 ?=" additive primes below ";350 ?=M+1
2 3 5 7 11 23 29 41 43 4761 67 83 89 101 113 131 137 139 151157 173 179 191 193 197 199 223 227 229241 263 269 281 283 311 313 317 331 337353 359 373 379 397 401 409 421 443 449461 463 467 487There are 54 additive primes below 500
import"./math"forIntimport"./fmt"forFmtvarsumDigits=Fn.new{|n|varsum=0while(n>0){sum=sum+(n%10)n=(n/10).floor}returnsum}System.print("Additive primes less than 500:")varprimes=Int.primeSieve(499)varcount=0for(pinprimes){if(Int.isPrime(sumDigits.call(p))){count=count+1Fmt.write("$3d ",p)if(count%10==0)System.print()}}System.print("\n\n%(count) additive primes found.")
Additive primes less than 500: 2 3 5 7 11 23 29 41 43 47 61 67 83 89 101 113 131 137 139 151 157 173 179 191 193 197 199 223 227 229 241 263 269 281 283 311 313 317 331 337 353 359 373 379 397 401 409 421 443 449 461 463 467 487 54 additive primes found.
func IsPrime(N); \Return 'true' if N is a prime numberint N, I;[if N <= 1 then return false;for I:= 2 to sqrt(N) do if rem(N/I) = 0 then return false;return true;];func SumDigits(N); \Return the sum of the digits in Nint N, Sum;[Sum:= 0;repeat N:= N/10; Sum:= Sum + rem(0);until N=0;return Sum;];int Count, N;[Count:= 0;for N:= 0 to 500-1 do if IsPrime(N) & IsPrime(SumDigits(N)) then [IntOut(0, N); Count:= Count+1; if rem(Count/10) = 0 then CrLf(0) else ChOut(0, 9\tab\); ];CrLf(0);IntOut(0, Count);Text(0, " additive primes found below 500.");]
2 3 5 7 11 23 29 41 43 4761 67 83 89 101 113 131 137 139 151157 173 179 191 193 197 199 223 227 229241 263 269 281 283 311 313 317 331 337353 359 373 379 397 401 409 421 443 449461 463 467 487 54 additive primes found below 500.
// Rosetta Code problem: http://rosettacode.org/wiki/Additive_primes// by Galileo, 06/2022limit = 500dim flags(limit)for i = 2 to limit for k = i*i to limit step i flags(k) = 1 next if flags(i) = 0 primes$ = primes$ + str$(i) + " "nextdim prim$(1)n = token(primes$, prim$())for i = 1 to n sum = 0 num$ = prim$(i) for j = 1 to len(num$) sum = sum + val(mid$(num$, j, 1)) next if instr(primes$, str$(sum) + " ") print prim$(i), " "; : count = count + 1nextprint "\nFound: ", count
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 487Found: 54---Program done, press RETURN---