Jump to content

Prime numbers p for which the sum of primes less than or equal to p is prime

From Rosetta Code
Prime numbers p for which the sum of primes less than or equal to p is prime is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
Task

Find primes   p   for which the sum of primes less than or equal to   p   is prime,   where   p  <  1,000.

ALGOL 68

Same as the Summarize primes#ALGOL_68 solution.

BEGIN # sum the primes below n and report the sums that are prime             #
    INT max prime = 999; # largest prime to consider                          #
    # sieve the primes to max prime #
    [ 1 : max prime ]BOOL prime;
    prime[ 1 ] := FALSE; prime[ 2 ] := TRUE;
    FOR i FROM 3 BY 2 TO UPB prime DO prime[ i ] := TRUE  OD;
    FOR i FROM 4 BY 2 TO UPB prime DO prime[ i ] := FALSE OD;
    FOR i FROM 3 BY 2 TO ENTIER sqrt( max prime ) DO
        IF prime[ i ] THEN FOR s FROM i * i BY i + i TO UPB prime DO prime[ s ] := FALSE OD FI
    OD;
    # sum the primes and test the sum                                         #
    INT prime sum       := 0;
    INT prime count     := 0;
    INT prime sum count := 0;
    print( ( "prime         prime", newline ) );
    print( ( "count  prime    sum", newline ) );
    FOR i TO max prime DO
        IF prime[ i ] THEN
            # have another prime                                              #
            prime count  +:= 1;
            prime sum    +:= i;
            # check whether the prime sum is prime or not                     #
            BOOL is prime := TRUE;
            FOR p TO i OVER 2 WHILE is prime DO
                IF prime[ p ] THEN is prime := prime sum MOD p /= 0 FI
            OD;
            IF is prime THEN
                # the prime sum is also prime                                 #
                prime sum count +:= 1;
                print( ( whole( prime count, -5 )
                       , " "
                       , whole( i,           -6 )
                       , " "
                       , whole( prime sum,   -6 )
                       , newline
                       )
                     )
            FI
        FI
    OD;
    print( ( newline
           , "Found "
           , whole( prime sum count, 0 )
           , " prime sums of primes below "
           , whole( max prime + 1, 0 )
           , newline
           )
         )
END
Output:
prime         prime
count  prime    sum
    1      2      2
    2      3      5
    4      7     17
    6     13     41
   12     37    197
   14     43    281
   60    281   7699
   64    311   8893
   96    503  22039
  100    541  24133
  102    557  25237
  108    593  28697
  114    619  32353
  122    673  37561
  124    683  38921
  130    733  43201
  132    743  44683
  146    839  55837
  152    881  61027
  158    929  66463
  162    953  70241

Found 21 prime sums of primes below 1000

Arturo

primes: select 1..1000 => prime?

pprimes: select primes 'x ->
    prime? sum select primes 'y -> y =< x

loop split.every:7 pprimes 'x ->
    print map x 's -> pad to :string s 4
Output:
   2    3    7   13   37   43  281 
 311  503  541  557  593  619  673 
 683  733  743  839  881  929  953

AWK

# syntax: GAWK -f PRIME_NUMBERS_P_WHICH_SUM_OF_PRIME_NUMBERS_LESS_OR_EQUAL_TO_P_IS_PRIME.AWK
BEGIN {
    start = 1
    stop = 999
    for (i=start; i<=stop; i++) {
      if (is_prime(i)) {
        sum += i
        if (is_prime(sum)) {
          printf("%4d%1s",i,++count%10?"":"\n")
        }
      }
    }
    printf("\n%d-%d: %d\n",start,stop,count)
    exit(0)
}
function is_prime(x,  i) {
    if (x <= 1) {
      return(0)
    }
    for (i=2; i<=int(sqrt(x)); i++) {
      if (x % i == 0) {
        return(0)
      }
    }
    return(1)
}
Output:
   2    3    7   13   37   43  281  311  503  541
 557  593  619  673  683  733  743  839  881  929
 953
1-999: 21

Delphi

Works with: Delphi version 6.0


procedure ShowPrimeLesserSum(Memo: TMemo);
var N,Sum,Cnt: integer;
var S: string;
begin
Cnt:=0;
Sum:=0;
for N:=2 to 1000-1 do
 if IsPrime(N) then
	begin
	Sum:=Sum+N;
	if IsPrime(Sum) then
		begin
		Inc(Cnt);
		S:=S+Format('%4d',[N]);
		If (Cnt mod 5)=0 then S:=S+CRLF;
		end;
	end;
Memo.Lines.Add(S);
Memo.Lines.Add('Count='+IntToStr(Cnt));
end;
Output:
   2   3   7  13  37
  43 281 311 503 541
 557 593 619 673 683
 733 743 839 881 929
 953
Count=21
Elapsed Time: 2.006 ms.


EasyLang

fastfunc isprim num .
   i = 2
   while i <= sqrt num
      if num mod i = 0
         return 0
      .
      i += 1
   .
   return 1
.
fastfunc nextprim prim .
   repeat
      prim += 1
      until isprim prim = 1
   .
   return prim
.
prim = 2
repeat
   sum += prim
   if isprim sum = 1
      write prim & " "
   .
   prim = nextprim prim
   until prim >= 1000
.
Output:
2 3 7 13 37 43 281 311 503 541 557 593 619 673 683 733 743 839 881 929 953 

F#

This task uses Extensible Prime Generator (F#)

// Primes (+)2..p is prime. Nigel Galloway: July 7th., 2021
primes32()|>Seq.takeWhile((>)1000)|>Seq.scan(fun(n,_) g->(n+g,g))(0,0)|>Seq.filter(fun(n,_)->isPrime n)|>Seq.iter(fun(_,n)->printf "%d " n); printfn ""

Factor

Works with: Factor version 0.99 2021-06-02
USING: assocs assocs.extras kernel math.primes math.statistics
prettyprint ;

1000 primes-upto dup cum-sum zip [ prime? ] filter-values .
Output:
{
    { 2 2 }
    { 3 5 }
    { 7 17 }
    { 13 41 }
    { 37 197 }
    { 43 281 }
    { 281 7699 }
    { 311 8893 }
    { 503 22039 }
    { 541 24133 }
    { 557 25237 }
    { 593 28697 }
    { 619 32353 }
    { 673 37561 }
    { 683 38921 }
    { 733 43201 }
    { 743 44683 }
    { 839 55837 }
    { 881 61027 }
    { 929 66463 }
    { 953 70241 }
}


FreeBASIC

Dim As Integer column = 0, sum = 0, limit = 1000

Color 10 : Print !"N£meros primos 'p' menores de"; limit; _
!"\ncuya suma de todos los n£meros "; _
!"\nprimos <= p tambi‚n es primo:\n" : Color 7

For n As Integer = 1 To limit
    If isprime(n) Then
        sum += n
        If isPrime(sum) Then  
            Print Using " ###"; n;
            column += 1
            If column Mod 7 = 0 Then Print : End If
        End If
    End If
Next n

Color 10 : Print !"\n\nEncontrados "; column; " n£meros."
Sleep
Output:
Números primos 'p' menores de 1000
cuya suma de todos los números
primos <= p también es primo:

    2   3   7  13  37  43 281
  311 503 541 557 593 619 673
  683 733 743 839 881 929 953

Encontrados  21 números.

Go

Translation of: Wren
package main

import (
    "fmt"
    "rcu"
)

func main() {
    primes := rcu.Primes(1000)
    maxSum := 0
    for _, p := range primes {
        maxSum += p
    }
    c := rcu.PrimeSieve(maxSum, true)
    primeSum := 0
    var results []int
    for _, p := range primes {
        primeSum += p
        if !c[primeSum] {
            results = append(results, p)
        }
    }
    fmt.Println("Primes 'p' under 1000 where the sum of all primes <= p is also prime:")
    for i, p := range results {
        fmt.Printf("%4d ", p)
        if (i+1)%7 == 0 {
            fmt.Println()
        }
    }
    fmt.Println("\nFound", len(results), "such primes")
}
Output:
Primes 'p' under 1000 where the sum of all primes <= p is also prime:
   2    3    7   13   37   43  281 
 311  503  541  557  593  619  673 
 683  733  743  839  881  929  953 

Found 21 such primes

J

(#~ 1 p: +/\)@(i.&.(p:^:_1)) 1000
Output:
2 3 7 13 37 43 281 311 503 541 557 593 619 673 683 733 743 839 881 929 953

jq

Works with: jq

Works with gojq, the Go implementation of jq

This entry adopts the straightforward approach as used for example in the awk entry. The jq implementation of this approach also turns out to be significantly faster than the jq implementation of the approach used in the Wren entry.

See Erdős-primes#jq for a suitable definition of `is_prime` as used here.

def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;

# Output: a stream of primes in range(0;$n)
def primes($n):
  2, (range(3;$n;2) | select(is_prime));

# Output: a stream of primes satisfying the condition
def results($n):
  foreach primes($n) as $p (0;
    . + $p;
    select(is_prime) | $p );

def task($n):
  "Primes 'p' under \($n) for which the sum of primes <= p is also prime:",
  ( [results($n)]
    | (_nwise(7) | map(lpad(4)) | join(" ")),
      "\nFound \(length) such primes." );

task(1000)
Output:
Primes 'p' under 1000 for which the sum of primes <= p is also prime:
   2    3    7   13   37   43  281
 311  503  541  557  593  619  673
 683  733  743  839  881  929  953

Found 21 such primes.

Julia

using Primes

primesumto(N) = begin s = 0; [i => s for i in 1:N if isprime(i) && isprime(s += i)] end

const primesumdict = primesumto(1000)

println("Prime  Prime Sum to Prime\n---------------------------")
for p in primesumdict
    println(rpad(p[1], 7), p[2])
end
println("\nTotal such primes < 1000: ", length(primesumdict))
Output:
Prime  Prime Sum to Prime
---------------------------
2      2
3      5
7      17
13     41
37     197
43     281
281    7699
311    8893
503    22039
541    24133
557    25237
593    28697
619    32353
673    37561
683    38921
733    43201
743    44683
839    55837
881    61027
929    66463
953    70241

Total such primes < 1000: 21

Mathematica / Wolfram Language

cands = Most@NestWhileList[NextPrime, 2, # < 1000 &];
Partition[
  cands[[Flatten@Position[PrimeQ /@ Accumulate[cands], True]]], 
  UpTo[5]] // TableForm
Output:

2 3 7 13 37 43 281 311 503 541 557 593 619 673 683 733 743 839 881 929 953

MiniScript

isPrime = function(n)
	if n <= 3 then return n > 1
	if n % 2 == 0 or n % 3 == 0 then return false
	
	i = 5
	while i ^ 2 <= n
		if n % i == 0 or n % (i + 2) == 0 then return false
		i += 6
	end while
	return true
end function

primes = []
sum = 0
for n in range(2, 1000)
	if isPrime(n) then
		sum += n
		if isPrime(sum) then primes.push(n)
	end if
end for
print primes.len + " found: " + primes


Output:
21 found: [2, 3, 7, 13, 37, 43, 281, 311, 503, 541, 557, 593, 619, 673, 683, 733, 743, 839, 881, 929, 953

Nim

import strutils, sugar

const
  N = 1000 - 1            # Maximum value for prime.
  S = N * (N + 1) div 2   # Maximum value for sum.

var composite: array[2..S, bool]
for n in 2..S:
  let n2 = n * n
  if n2 > S: break
  if not composite[n]:
    for k in countup(n2, S, n):
      composite[k] = true

template isPrime(n: int): bool = not composite[n]

let primes = collect:
                 for n in 2..N:
                   if n.isPrime: n

var list: seq[int]
var sum = 0
for p in primes:
  sum += p
  if sum.isPrime:
    list.add p

echo "Found $# primes:".format(list.len)
echo list.join(" ")
Output:
Found 21 primes:
2 3 7 13 37 43 281 311 503 541 557 593 619 673 683 733 743 839 881 929 953

Perl

#!/usr/bin/perl

use strict; # https://rosettacode.org/wiki/Prime_numbers_p_which_sum_of_prime_numbers_less_or_equal_to_p_is_prime
use warnings;
use ntheory qw( is_prime primes vecsum );

print "@{[ grep is_prime( vecsum( @{ primes($_) } ) ), @{ primes(1000) } ]}\n";
Output:
2 3 7 13 37 43 281 311 503 541 557 593 619 673 683 733 743 839 881 929 953

Phix

As per Raku, this is pretty much an exact duplicate of Summarize_primes#Phix, bar output of primes instead of their index.

function sump(integer p, i, sequence s) return is_prime(sum(s[1..i])) end function
sequence res = filter(get_primes_le(1000),sump)
printf(1,"%d found: %V\n",{length(res),res})
Output:
21 found: {2,3,7,13,37,43,281,311,503,541,557,593,619,673,683,733,743,839,881,929,953}

Prolog

runs with swi-prolog

primes(2, Limit):- 2 =< Limit.
primes(3, Limit):- 3 =< Limit.
primes(N, Limit):-
	between(5, Limit, N),
	N /\ 1 > 0,             % odd
	N mod 3 > 0,		    % /= 3*i
	M is floor(sqrt(N)) + 1, % reverse 6*I-1
	Max is M div 6,
	forall(between(1, Max, I), (N mod (6*I-1) > 0, N mod (6*I+1) > 0)).

isPrime(N):-
	primes(N, inf).

primeSum(List, LastP):-
	append(SubList, _, List),
	sum_list(SubList, Sum),
	isPrime(Sum),
	last(SubList, LastP).

showList(List):-
	last(List, Last),
	FmtLen is 2 + floor(log10(Last)),	% one more for space
	swritef(FmtStr, '%%dr', [FmtLen]),
	findnsols(10, X, (member(X, List), writef(FmtStr, [X])), _), nl,
	fail.
showList(_).

do(Limit):-
	findall(N, primes(N, Limit), PrimeList),
	findall(LastP, primeSum(PrimeList, LastP), SumList),
	showList(SumList).

do:- do(2000).
Output:
?- do.
    2    3    7   13   37   43  281  311  503  541
  557  593  619  673  683  733  743  839  881  929
  953 1061 1163 1213 1249 1277 1283 1307 1321 1949
true.

Python

def prime(n):
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

p = []
x = 1
lis = []


for i in range(0, 1000):
    x += 1
    if prime(x) == True:
        p.append(x)
        str_x = str(x)
        if prime(sum(p)) == True:
                lis.append(x)
    if int(x) == 1000:
        print(f'Found {len(lis)} primes less than 1000')
        for i in lis:
            print(i)
Output:
Found 21 primes less than 1000
2
3
7
13
37
43
281
311
503
541
557
593
619
673
683
733
743
839
881
929
953


Quackery

isprime is defined at Primality by trial division#Quackery.

  0 1000 times [ i^ isprime if [ i^ + dup isprime if [ i^ echo sp ] drop ] ]
Output:
2 3 7 13 37 43 281 311 503 541 557 593 619 673 683 733 743 839 881 929 953

Raku

Trivial variation of Summarize primes task. Modified to do double duty.

use Lingua::EN::Numbers;

my @primes    = grep *.is-prime, ^Inf;
my @primesums = [\+] @primes;
say "{.elems} cumulative prime sums:\n",
    .map( -> $p {
        sprintf "The sum of the first %3d (up to {@primes[$p]}) is prime: %s",
        1 + $p, comma @primesums[$p]
      }
    ).join("\n")
    given grep { @primesums[$_].is-prime }, ^1000;
Output:
76 cumulative prime sums:
The sum of the first   1 (up to 2) is prime: 2
The sum of the first   2 (up to 3) is prime: 5
The sum of the first   4 (up to 7) is prime: 17
The sum of the first   6 (up to 13) is prime: 41
The sum of the first  12 (up to 37) is prime: 197
The sum of the first  14 (up to 43) is prime: 281
The sum of the first  60 (up to 281) is prime: 7,699
The sum of the first  64 (up to 311) is prime: 8,893
The sum of the first  96 (up to 503) is prime: 22,039
The sum of the first 100 (up to 541) is prime: 24,133
The sum of the first 102 (up to 557) is prime: 25,237
The sum of the first 108 (up to 593) is prime: 28,697
The sum of the first 114 (up to 619) is prime: 32,353
The sum of the first 122 (up to 673) is prime: 37,561
The sum of the first 124 (up to 683) is prime: 38,921
The sum of the first 130 (up to 733) is prime: 43,201
The sum of the first 132 (up to 743) is prime: 44,683
The sum of the first 146 (up to 839) is prime: 55,837
The sum of the first 152 (up to 881) is prime: 61,027
The sum of the first 158 (up to 929) is prime: 66,463
The sum of the first 162 (up to 953) is prime: 70,241
The sum of the first 178 (up to 1061) is prime: 86,453
The sum of the first 192 (up to 1163) is prime: 102,001
The sum of the first 198 (up to 1213) is prime: 109,147
The sum of the first 204 (up to 1249) is prime: 116,533
The sum of the first 206 (up to 1277) is prime: 119,069
The sum of the first 208 (up to 1283) is prime: 121,631
The sum of the first 214 (up to 1307) is prime: 129,419
The sum of the first 216 (up to 1321) is prime: 132,059
The sum of the first 296 (up to 1949) is prime: 263,171
The sum of the first 308 (up to 2029) is prime: 287,137
The sum of the first 326 (up to 2161) is prime: 325,019
The sum of the first 328 (up to 2203) is prime: 329,401
The sum of the first 330 (up to 2213) is prime: 333,821
The sum of the first 332 (up to 2237) is prime: 338,279
The sum of the first 334 (up to 2243) is prime: 342,761
The sum of the first 342 (up to 2297) is prime: 360,979
The sum of the first 350 (up to 2357) is prime: 379,667
The sum of the first 356 (up to 2393) is prime: 393,961
The sum of the first 358 (up to 2411) is prime: 398,771
The sum of the first 426 (up to 2957) is prime: 581,921
The sum of the first 446 (up to 3137) is prime: 642,869
The sum of the first 458 (up to 3251) is prime: 681,257
The sum of the first 460 (up to 3257) is prime: 687,767
The sum of the first 464 (up to 3301) is prime: 700,897
The sum of the first 480 (up to 3413) is prime: 754,573
The sum of the first 484 (up to 3461) is prime: 768,373
The sum of the first 488 (up to 3491) is prime: 782,263
The sum of the first 512 (up to 3671) is prime: 868,151
The sum of the first 530 (up to 3821) is prime: 935,507
The sum of the first 536 (up to 3863) is prime: 958,577
The sum of the first 548 (up to 3947) is prime: 1,005,551
The sum of the first 568 (up to 4129) is prime: 1,086,557
The sum of the first 620 (up to 4583) is prime: 1,313,041
The sum of the first 630 (up to 4657) is prime: 1,359,329
The sum of the first 676 (up to 5051) is prime: 1,583,293
The sum of the first 680 (up to 5087) is prime: 1,603,597
The sum of the first 696 (up to 5233) is prime: 1,686,239
The sum of the first 708 (up to 5351) is prime: 1,749,833
The sum of the first 734 (up to 5563) is prime: 1,891,889
The sum of the first 762 (up to 5807) is prime: 2,051,167
The sum of the first 768 (up to 5849) is prime: 2,086,159
The sum of the first 776 (up to 5897) is prime: 2,133,121
The sum of the first 780 (up to 5939) is prime: 2,156,813
The sum of the first 784 (up to 6007) is prime: 2,180,741
The sum of the first 808 (up to 6211) is prime: 2,327,399
The sum of the first 814 (up to 6263) is prime: 2,364,833
The sum of the first 820 (up to 6301) is prime: 2,402,537
The sum of the first 836 (up to 6427) is prime: 2,504,323
The sum of the first 844 (up to 6529) is prime: 2,556,187
The sum of the first 848 (up to 6563) is prime: 2,582,401
The sum of the first 852 (up to 6581) is prime: 2,608,699
The sum of the first 926 (up to 7243) is prime: 3,120,833
The sum of the first 942 (up to 7433) is prime: 3,238,237
The sum of the first 984 (up to 7757) is prime: 3,557,303
The sum of the first 992 (up to 7853) is prime: 3,619,807

REXX

/*REXX program finds primes in which sum of primes  ≤  P  is prime,  where  P  <  1.000.*/
parse arg hi cols .                              /*obtain optional argument from the CL.*/
if   hi=='' |   hi==","  then   hi= 1000         /*Not specified?  Then use the default.*/
if cols=='' | cols==","  then cols=   10         /* "      "         "   "   "     "    */
call genP                                        /*build array of semaphores for primes.*/
w= 10                                            /*the width of a number in any column. */
title= ' primes which the sum of primes  ≤  P  is prime,  where  P  < '     commas(hi)
say ' index │' center(title, 1 + cols*(w+1)     )
say '───────┼'center(""    , 1 + cols*(w+1), '─')
found= 0;                           idx = 1      /*number of primes found (so far); IDX.*/
$=;                                 pSum= 0      /*#: list of primes (so far); init pSum*/
        do j=1  for hi-1;  p= @.j;  pSum= pSum+p /*find summation primes within range.  */
        if \!.pSum  then iterate                 /*Is sum─of─primes a prime?  Then skip.*/
        found= found + 1                         /*bump the number of found  primes.    */
        if cols<0             then iterate       /*Build the list  (to be shown later)? */
        c= commas(p)                             /*maybe add commas to the number.      */
        $= $ right(c, max(w, length(c) ) )       /*add a found prime──►list, allow big #*/
        if found//cols\==0    then iterate       /*have we populated a line of output?  */
        say center(idx, 7)'│'  substr($, 2);  $= /*display what we have so far  (cols). */
        idx= idx + cols                          /*bump the  index  count for the output*/
        end   /*j*/

if $\==''  then say center(idx, 7)"│"  substr($, 2)  /*possible display residual output.*/
say '───────┴'center(""    , 1 + cols*(w+1), '─')
say
say 'Found '       commas(found)      title
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?;  do jc=length(?)-3  to 1  by -3; ?=insert(',', ?, jc); end;  return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: !.= 0;  sP= 0                              /*prime semaphores;  sP= sum of primes.*/
      @.1=2;  @.2=3;  @.3=5;  @.4=7;  @.5=11     /*define some low primes.              */
      !.2=1;  !.3=1;  !.5=1;  !.7=1;  !.11=1     /*   "     "   "    "     flags.       */
                        #=5;     sq.#= @.# **2   /*number of primes so far;     prime². */
                                                 /* [↓]  generate more  primes  ≤  high.*/
        do j=@.#+2  by 2  until @.#>=hi & @.#>sP /*find odd primes where  P≥hi and P>sP.*/
        parse var j '' -1 _; if     _==5  then iterate  /*J divisible by 5?  (right dig)*/
                             if j// 3==0  then iterate  /*"     "      " 3?             */
                             if j// 7==0  then iterate  /*"     "      " 7?             */
               do k=5  while sq.k<=j             /* [↓]  divide by the known odd primes.*/
               if j // @.k == 0  then iterate j  /*Is  J ÷ X?  Then not prime.     ___  */
               end   /*k*/                       /* [↑]  only process numbers  ≤  √ J   */
        #= #+1;    @.#= j;    sq.#= j*j;  !.j= 1 /*bump # of Ps; assign next P;  P²; P# */
        if @.#<hi  then sP= sP + @.#             /*maybe add this prime to sum─of─primes*/
        end          /*j*/;               return
output   when using the default inputs:
 index │                       primes which the sum of primes  ≤  P  is prime,  where  P  <  1,000
───────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────
   1   │          2          3          7         13         37         43        281        311        503        541
  11   │        557        593        619        673        683        733        743        839        881        929
  21   │        953
───────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────

Found  21  primes which the sum of primes  ≤  P  is prime,  where  P  <  1,000

Ring

load "stdlib.ring"
see "working..." + nl
see "Prime numbers p which sum of prime numbers less or equal to p is prime:" + nl

row = 0
sum = 0
limit = 1000

for n = 1 to limit
    if isprime(n)
       sum = sum + n
       if isprime(sum)    
          see "" + n + " " 
          row++
          if row%5 = 0
             see nl
          ok
       ok
    ok
next

see nl + "Found " + row + " numbers" + nl
see "done..." + nl
Output:
working...
Prime numbers p which sum of prime numbers less or equal to p is prime:
2 3 7 13 37 
43 281 311 503 541 
557 593 619 673 683 
733 743 839 881 929 
953 
Found 21 numbers
done...

RPL

Works with: HP version 49
« { } 0 0
  WHILE DUP 1000 < REPEAT
     NEXTPRIME SWAP OVER + SWAP
     IF OVER ISPRIME? THEN ROT OVER + UNROT END
  END DROP2
» 'TASK' STO
Output:
1: { 2 3 7 13 37 43 281 311 503 541 557 593 619 673 683 733 743 839 881 929 953 }

Sidef

func primes_with_prime_sum(n, callback) {
    var s = 0
    n.each_prime {|p|
        s += p
        callback(p, s) if s.is_prime
    }
}

primes_with_prime_sum(1000, {|p,s|
    say "prime: #{'%3s' % p}   prime sum: #{'%5s' % s}"
})
Output:
prime:   2   prime sum:     2
prime:   3   prime sum:     5
prime:   7   prime sum:    17
prime:  13   prime sum:    41
prime:  37   prime sum:   197
prime:  43   prime sum:   281
prime: 281   prime sum:  7699
prime: 311   prime sum:  8893
prime: 503   prime sum: 22039
prime: 541   prime sum: 24133
prime: 557   prime sum: 25237
prime: 593   prime sum: 28697
prime: 619   prime sum: 32353
prime: 673   prime sum: 37561
prime: 683   prime sum: 38921
prime: 733   prime sum: 43201
prime: 743   prime sum: 44683
prime: 839   prime sum: 55837
prime: 881   prime sum: 61027
prime: 929   prime sum: 66463
prime: 953   prime sum: 70241

Uiua

Works with: Uiua version 0.10.0-dev.1
# Build primes by sieve. Limit found by inspection.
⇌◌⍢(▽≠0◿⊃⊢(.↘1)⟜(⊂⊢)|>0⧻) ↘2⇡80000 []
# Build running sums.
\+▽<1000...
# # Find sums that are prime, then prettify.
⧻.⍉⊟:∩(⬚0▽),⟜∊
Output:
╭─           
╷   2     2  
    3     5  
    7    17  
   13    41  
   37   197  
   43   281  
  281  7699  
  311  8893  
  503 22039  
  541 24133  
  557 25237  
  593 28697  
  619 32353  
  673 37561  
  683 38921  
  733 43201  
  743 44683  
  839 55837  
  881 61027  
  929 66463  
  953 70241  
            ╯
21

Wren

Library: Wren-math
Library: Wren-fmt
import "./math" for Int, Nums
import "./fmt" for Fmt

var primes = Int.primeSieve(1000, true)
var maxSum = Nums.sum(primes)
var c = Int.primeSieve(maxSum, false)
var primeSum = 0
var results = []
for (p in primes) {
   primeSum = primeSum + p
   if (!c[primeSum]) results.add(p)
}
System.print("Primes 'p' under 1000 where the sum of all primes <= p is also prime:")
Fmt.tprint("$4d", results, 7)
System.print("\nFound %(results.count) such primes.")
Output:
Primes 'p' under 1000 where the sum of all primes <= p is also prime:
   2    3    7   13   37   43  281
 311  503  541  557  593  619  673
 683  733  743  839  881  929  953

Found 21 such primes.

XPL0

func IsPrime(N);        \Return 'true' if N is a prime number
int  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;
];

int Count, N, Sum;
[Count:= 0;
Sum:= 0;
for N:= 2 to 1000-1 do
    if IsPrime(N) then
        [Sum:= Sum + N;
        if IsPrime(Sum) 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, " such numbers found below 1000.
");
]
Output:
2       3       7       13      37      43      281     311     503     541
557     593     619     673     683     733     743     839     881     929
953     
21 such numbers found below 1000.
Cookies help us deliver our services. By using our services, you agree to our use of cookies.