Prime numbers p for which the sum of primes less than or equal to p is prime: Difference between revisions
Prime numbers p for which the sum of primes less than or equal to p is prime (view source)
Revision as of 22:29, 4 April 2024
, 1 month agoAdded Uiua solution
m (→{{header|Sidef}}: use a callback function to be memory efficient for larger n) |
(Added Uiua solution) |
||
(18 intermediate revisions by 14 users not shown) | |||
Line 2:
;Task:
Find primes '''p''' for which the sum of primes less than or equal to '''p''' is prime, where '''p < 1,000'''.
<br><br>
=={{header|ALGOL 68}}==
Same as the [[Summarize primes#ALGOL_68]] solution.
<
INT max prime = 999; # largest prime to consider #
# sieve the primes to max prime #
Line 55:
)
)
END</
{{out}}
<pre>
Line 84:
Found 21 prime sums of primes below 1000
</pre>
=={{header|Arturo}}==
<syntaxhighlight lang="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</syntaxhighlight>
{{out}}
<pre> 2 3 7 13 37 43 281
311 503 541 557 593 619 673
683 733 743 839 881 929 953</pre>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f PRIME_NUMBERS_P_WHICH_SUM_OF_PRIME_NUMBERS_LESS_OR_EQUAL_TO_P_IS_PRIME.AWK
BEGIN {
Line 112 ⟶ 128:
return(1)
}
</syntaxhighlight>
{{out}}
<pre>
Line 120 ⟶ 136:
1-999: 21
</pre>
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
<syntaxhighlight lang="Delphi">
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;
</syntaxhighlight>
{{out}}
<pre>
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.
</pre>
=={{header|F_Sharp|F#}}==
This task uses [http://www.rosettacode.org/wiki/Extensible_prime_generator#The_functions 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 ""
</syntaxhighlight>
=={{header|Factor}}==
{{works with|Factor|0.99 2021-06-02}}
<
prettyprint ;
1000 primes-upto dup cum-sum zip [ prime? ] filter-values .</
{{out}}
<pre>
Line 162 ⟶ 220:
=={{header|FreeBASIC}}==
<
Dim As Integer column = 0, sum = 0, limit = 1000
Line 182 ⟶ 240:
Color 10 : Print !"\n\nEncontrados "; column; " n£meros."
Sleep
</syntaxhighlight>
{{out}}
<pre>
Line 198 ⟶ 256:
=={{header|Go}}==
{{trans|Wren}}
<
import (
Line 228 ⟶ 286:
}
fmt.Println("\nFound", len(results), "such primes")
}</
{{out}}
Line 238 ⟶ 296:
Found 21 such primes
</pre>
=={{header|J}}==
<syntaxhighlight lang="j">(#~ 1 p: +/\)@(i.&.(p:^:_1)) 1000</syntaxhighlight>
{{out}}
<pre>2 3 7 13 37 43 281 311 503 541 557 593 619 673 683 733 743 839 881 929 953</pre>
=={{header|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|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|Wren]] entry.
See [[Erdős-primes#jq]] for a suitable definition of `is_prime` as
used here.
<syntaxhighlight lang="jq">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)</syntaxhighlight>
{{out}}
<pre>
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.
</pre>
=={{header|Julia}}==
<
primesumto(N) = begin s = 0; [i => s for i in 1:N if isprime(i) && isprime(s += i)] end
Line 252 ⟶ 354:
end
println("\nTotal such primes < 1000: ", length(primesumdict))
</
<pre>
Prime Prime Sum to Prime
Line 280 ⟶ 382:
Total such primes < 1000: 21
</pre>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">cands = Most@NestWhileList[NextPrime, 2, # < 1000 &];
Partition[
cands[[Flatten@Position[PrimeQ /@ Accumulate[cands], True]]],
UpTo[5]] // TableForm</syntaxhighlight>
{{out}}<pre>
2 3 7 13 37
43 281 311 503 541
557 593 619 673 683
733 743 839 881 929
953
</pre>
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">
isPrime = function(n)
if n <= 3 then return n > 1
if n % 2 == 0 or n % 3 == 0 then return false
i = 5
while i ^ 2 <= n
if n % i == 0 or n % (i + 2) == 0 then return false
i += 6
end while
return true
end function
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
</syntaxhighlight>
{{out}}
<pre>
21 found: [2, 3, 7, 13, 37, 43, 281, 311, 503, 541, 557, 593, 619, 673, 683, 733, 743, 839, 881, 929, 953</pre>
=={{header|Nim}}==
<
const
Line 298 ⟶ 444:
template isPrime(n: int): bool = not composite[n]
let primes = collect
for n in 2..N:
if n.isPrime: n
Line 310 ⟶ 456:
echo "Found $# primes:".format(list.len)
echo list.join(" ")</
{{out}}
<pre>Found 21 primes:
2 3 7 13 37 43 281 311 503 541 557 593 619 673 683 733 743 839 881 929 953</pre>
=={{header|Perl}}==
<syntaxhighlight lang="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";</syntaxhighlight>
{{out}}
<pre>
2 3 7 13 37 43 281 311 503 541 557 593 619 673 683 733 743 839 881 929 953
</pre>
=={{header|Phix}}==
As per Raku, this is pretty much an exact duplicate of [[Summarize_primes#Phix]], bar output of primes instead of their index.
<!--<
<span style="color: #008080;">function</span> <span style="color: #000000;">sump</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #7060A8;">is_prime</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]))</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">filter</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">get_primes_le</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1000</span><span style="color: #0000FF;">),</span><span style="color: #000000;">sump</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d found: %V\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">),</span><span style="color: #000000;">res</span><span style="color: #0000FF;">})</span>
<!--</
{{out}}
<pre>
21 found: {2,3,7,13,37,43,281,311,503,541,557,593,619,673,683,733,743,839,881,929,953}
</pre>
=={{header|Prolog}}==
runs with swi-prolog
<syntaxhighlight lang="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).
</syntaxhighlight>
{{out}}
<pre>
?- 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.
</pre>
=={{header|Quackery}}==
<code>isprime</code> is defined at [[Primality by trial division#Quackery]].
<syntaxhighlight lang="Quackery"> 0 1000 times [ i^ isprime if [ i^ + dup isprime if [ i^ echo sp ] drop ] ]</syntaxhighlight>
{{out}}
<pre>2 3 7 13 37 43 281 311 503 541 557 593 619 673 683 733 743 839 881 929 953</pre>
=={{header|Raku}}==
Trivial variation of [[Summarize_primes#Raku|Summarize primes]] task. Modified to do double duty.
<syntaxhighlight lang="raku"
my @primes = grep *.is-prime, ^Inf;
Line 340 ⟶ 554:
}
).join("\n")
given grep { @primesums[$_].is-prime }, ^1000;</
{{out}}
<pre>76 cumulative prime sums:
Line 421 ⟶ 635:
=={{header|REXX}}==
<
parse arg hi cols . /*obtain optional argument from the CL.*/
if hi=='' | hi=="," then hi= 1000 /*Not specified? Then use the default.*/
Line 465 ⟶ 679:
#= #+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</
{{out|output|text= when using the default inputs:}}
<pre>
Line 479 ⟶ 693:
=={{header|Ring}}==
<
load "stdlib.ring"
see "working..." + nl
Line 503 ⟶ 717:
see nl + "Found " + row + " numbers" + nl
see "done..." + nl
</syntaxhighlight>
{{out}}
<pre>
Line 515 ⟶ 729:
Found 21 numbers
done...
</pre>
=={{header|RPL}}==
{{works with|HP|49}}
« { } 0 0
'''WHILE''' DUP 1000 < '''REPEAT'''
NEXTPRIME SWAP OVER + SWAP
'''IF''' OVER ISPRIME? '''THEN''' ROT OVER + UNROT '''END'''
'''END''' DROP2
» '<span style="color:blue">TASK</span>' STO
{{out}}
<pre>
1: { 2 3 7 13 37 43 281 311 503 541 557 593 619 673 683 733 743 839 881 929 953 }
</pre>
=={{header|Sidef}}==
<
var s = 0
n.each_prime {|p|
Line 528 ⟶ 755:
primes_with_prime_sum(1000, {|p,s|
say "prime: #{'%3s' % p} prime sum: #{'%5s' % s}"
})</
{{out}}
<pre>
Line 552 ⟶ 779:
prime: 929 prime sum: 66463
prime: 953 prime sum: 70241
</pre>
=={{header|Uiua}}==
{{works with|Uiua|0.10.0-dev.1}}
<syntaxhighlight lang="Uiua">
# 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▽),⟜∊
</syntaxhighlight>
{{out}}
<pre>
╭─
╷ 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
</pre>
=={{header|Wren}}==
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
<
import "./
var primes = Int.primeSieve(1000, true)
Line 572 ⟶ 836:
}
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.")</
{{out}}
Line 586 ⟶ 850:
=={{header|XPL0}}==
<
int N, I;
[if N <= 1 then return false;
Line 610 ⟶ 874:
Text(0, " such numbers found below 1000.
");
]</
{{out}}
<pre>2 3 7 13 37 43 281 311 503 541
557 593 619 673 683 733 743 839 881 929
953
|