CalmoSoft primes: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(47 intermediate revisions by 12 users not shown)
Line 6:
Find and show here the longest sequence of CalmoSoft primes for p(n) < 100.
;Stretch
Show a shortened version (first and last 6 primes) of the same for p(n) < fifty million.<br>
Tip: if it takes longer than twotwenty seconds, you're doing it wrong.
 
<br><br>
=={{header|ALGOL 68}}==
If there are multiple sequences with the maximum length, this will only show the first.
===Basic task===
<syntaxhighlight lang="algol68">
BEGIN # find the longest sequence of primes < 100 that sums to a prime #
Line 25 ⟶ 26:
ELSE
BOOL is a prime := TRUE;
FOR f FROM 5 BY 2 WHILE f * f <= n AND ( is a prime := n MOD f /= 0 )DO
DO SKIP OD; is a prime := n MOD f /= 0
OD;
is a prime
FI # is prime # ;
Line 36 ⟶ 38:
INT max len := -1;
INT max sum := -1;
FOR this start FROM LWB prime TO UPB prime - 1 DO
WHILE
INT this end := UPB prime;
INT this len := ( this end + 1 ) - this start;
Line 57 ⟶ 60:
FI
FI;
( UPB prime - this start ) > max len
DO
# the start prime won't be in the next sequence #
seq sum -:= prime[ this start ]
Line 73 ⟶ 78:
7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89
</pre>
 
===Stretch===
Basically the same algorithm as the Algol 68 Basic task sample but stops searching when there can't be a longer sequence.
<br>Also, if the first prime in the sequence is 2, the sequence must have even length, otherwise it must have odd length.
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Uses Algol 68G's LONG LONG INT for the Millar Rabin test.
To run this with Algol 68G, you need <code>-heap 512M</code> on the command line.
<br>Note the source of the <code>is probably prime</code> routine used here is available from a page in Rosetta Code - see the following link.
{{libheader|ALGOL 68-primes}}
<syntaxhighlight lang="algol68">
BEGIN # find the longest sequence of primes < 50 000 000 that sums to a prime#
# called Calmosoft primes #
PR read "primes.incl.a68" PR
INT max prime = 50 000 000;
# sieve, count and sum the primes to max prime and replace the sieve #
# with a list of primes #
[ 1 : max prime ]INT prime;
INT yes = 1, no = 0;
prime[ 1 ] := 2; # the first prime in the list #
prime[ 2 ] := yes; # first TRUE sieve value #
INT p count := 1;
LONG INT p sum := 2;
FOR i FROM 3 BY 2 TO UPB prime DO prime[ i ] := yes OD;
FOR i FROM 4 BY 2 TO UPB prime DO prime[ i ] := no OD;
INT root max prime = ENTIER sqrt( UPB prime );
FOR i FROM 3 BY 2 TO root max prime DO
IF prime[ i ] = yes THEN
prime[ p count +:= 1 ] := i;
p sum +:= i;
FOR s FROM i * i BY i + i TO UPB prime DO prime[ s ] := no OD
FI
OD;
FOR i FROM root max prime + IF ODD root max prime THEN 2 ELSE 1 FI BY 2 TO max prime DO
IF prime[ i ] = yes THEN
prime[ p count +:= 1 ] := i;
p sum +:= i
FI
OD;
LONG INT seq sum := p sum;
# find the longest sequence that sums to a prime #
INT max start := -1;
INT max end := -1;
INT max len := -1;
LONG INT max sum := -1;
FOR this start TO p count - 1
WHILE
INT this end := p count;
INT this len := ( this end + 1 ) - this start;
LONG INT this sum := seq sum;
IF ODD this len THEN
IF this start = 1 THEN
# the first prime is 2, the sequence must have even length #
this sum -:= prime[ this end ];
this end -:= 1;
this len -:= 1
FI
ELSE
IF this start > 1 THEN
# the first prime isn't 2, the sequence must have odd length #
this sum -:= prime[ this end ];
this end -:= 1;
this len -:= 1
FI
FI;
IF this len > max len THEN
BOOL this prime := FALSE;
WHILE IF this end < this start OR this len < max len
THEN FALSE
ELSE NOT ( this prime := is probably prime( this sum ) )
FI
DO
this sum -:= prime[ this end ];
this sum -:= prime[ this end -:= 1 ];
this end -:= 1;
this len -:= 2
OD;
IF this prime AND this len > max len THEN
max len := this len; # found a longer sequence #
max start := this start;
max end := this end;
max sum := this sum
FI
FI;
( p count - this start ) > max len
DO
# the start prime won't be in the next sequence #
seq sum -:= prime[ this start ]
OD;
print( ( "Longest sequence of Calmosoft primes up to ", whole( prime[ p count ], 0 )
, " has sum ", whole( max sum, 0 ), " and length ", whole( max len, 0 )
, newline
)
);
IF max len < 12 THEN
FOR i FROM max start TO max end DO print( ( " ", whole( prime[ i ], 0 ) ) ) OD
ELSE
FOR i FROM max start TO max start + 6 DO print( ( " ", whole( prime[ i ], 0 ) ) ) OD;
print( ( " ... " ) );
FOR i FROM max end - 6 TO max end DO print( ( " ", whole( prime[ i ], 0 ) ) ) OD
FI
END
</syntaxhighlight>
{{out}}
<pre>
Longest sequence of Calmosoft primes up to 49999991 has sum 72618848632313 and length 3001117
7 11 13 17 19 23 29 ... 49999693 49999699 49999711 49999739 49999751 49999753 49999757
</pre>
 
=={{header|AppleScript}}==
''"Tip: if it takes longer than twenty seconds, you're doing it wrong."'' It largely depends of course on the speed and busy-ness of the computer, the characteristics of the language, and which part of the process you're timing. :) On my current machine, the code below takes 70-71 seconds to perform the two tasks together, most of which time is spent just getting the primes < 50,000,000 for the stretch. The rest of the stretch only takes just under three seconds and everything else is crammed into 0.002 seconds.
<syntaxhighlight lang="applescript">-- Find the longest run of "CalmoSoft primes" ≤ limit.
on CalmoSoftPrimes(limit)
script o
property primes : sieveOfSundaram(2, limit)
end script
set maxSum to 0
repeat with p in o's primes
set maxSum to maxSum + p
end repeat
if (isPrime(maxSum)) then return {sum:maxSum, |run|:o's primes}
set {j, topRunLen} to {count o's primes, 0}
repeat while (j > topRunLen)
set testSum to maxSum
repeat with i from 1 to (j - topRunLen)
set testSum to testSum - (o's primes's item i)
if (isPrime(testSum)) then exit repeat
end repeat
set runLen to j - i
if (runLen > topRunLen) then
set topRunLen to runLen
set topRunStart to i + 1
set topRunEnd to j
set topRunSum to testSum
end if
set maxSum to maxSum - (o's primes's item j)
set j to j - 1
end repeat
return {sum:topRunSum, |run|:o's primes's items topRunStart thru topRunEnd}
end CalmoSoftPrimes
 
on sieveOfSundaram(lowerLimit, upperLimit)
if (upperLimit < lowerLimit) then set {upperLimit, lowerLimit} to {lowerLimit, upperLimit}
if (upperLimit < 2) then return {}
if (lowerLimit < 2) then set lowerLimit to 2
set k to (upperLimit - 1) div 2
set shift to lowerLimit div 2 - 1
script o
property sieve : makeList(k - shift, true)
on zapMultiples(n)
set i to (n * n) div 2
if (i ≤ shift) then set i to shift + n - (shift - i) mod n
repeat with i from (i - shift) to (k - shift) by n
set my sieve's item i to false
end repeat
end zapMultiples
end script
o's zapMultiples(3)
set addends to {2, 6, 8, 12, 14, 18, 24, 26}
repeat with n from 5 to (upperLimit ^ 0.5 div 1) by 30
o's zapMultiples(n)
repeat with a in addends
o's zapMultiples(n + a)
end repeat
end repeat
repeat with i from 1 to (k - shift)
if (o's sieve's item i) then set o's sieve's item i to (i + shift) * 2 + 1
end repeat
set o's sieve to o's sieve's numbers
if (lowerLimit is 2) then set o's sieve's beginning to 2
return o's sieve
end sieveOfSundaram
 
on makeList(limit, filler)
if (limit < 1) then return {}
script o
property lst : {filler}
end script
set counter to 1
repeat until (counter + counter > limit)
set o's lst to o's lst & o's lst
set counter to counter + counter
end repeat
if (counter < limit) then set o's lst to o's lst & o's lst's items 1 thru (limit - counter)
return o's lst
end makeList
 
on isPrime(n)
if (n < 4) then return (n > 1)
if ((n mod 2 is 0) or (n mod 3 is 0)) then return false
repeat with i from 5 to (n ^ 0.5) div 1 by 6
if ((n mod i is 0) or (n mod (i + 2) is 0)) then return false
end repeat
return true
end isPrime
 
on join(lst, delim)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set txt to lst as text
set AppleScript's text item delimiters to astid
return txt
end join
 
on intToText(int, separator)
set groups to {}
repeat while (int > 999)
set groups's beginning to ((1000 + (int mod 1000 as integer)) as text)'s text 2 thru 4
set int to int div 1000
end repeat
set groups's beginning to int
return join(groups, separator)
end intToText
 
on task()
set output to {"Longest run of CalmoSoft primes < 100:"}
set {sum:sum, |run|:|run|} to CalmoSoftPrimes(99)
set end of output to join(|run|, ", ")
set end of output to "They add up to " & sum
set end of output to "Beginning & end of longest run of CalmoSoft primes < 50,000,000:"
script o
property |run| : missing value
end script
set {sum:sum, |run|:o's |run|} to CalmoSoftPrimes(49999999)
set end of output to join(o's |run|'s items 1 thru 6, ", ") & " … " & join(o's |run|'s items -6 thru -1, ", ")
set end of output to "The entire run adds up to " & intToText(sum, ",")
return join(output, linefeed)
end task
 
task()</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">"Longest run of CalmoSoft primes < 100:
7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89
They add up to 953
Beginning & end of longest run of CalmoSoft primes < 50,000,000:
7, 11, 13, 17, 19, 23 … 49999699, 49999711, 49999739, 49999751, 49999753, 49999757
The entire run adds up to 72,618,848,632,313"</syntaxhighlight>
 
=={{header|Arturo}}==
Line 101 ⟶ 354:
 
[7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89]</pre>
 
=={{header|C}}==
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdbool.h>
#include <string.h>
 
bool isPrime(int n) {
if (n < 2) return false;
if (n%2 == 0) return n == 2;
if (n%3 == 0) return n == 3;
int d = 5;
while (d*d <= n) {
if (n%d == 0) return false;
d += 2;
if (n%d == 0) return false;
d += 4;
}
return true;
}
 
int main() {
int primes[30] = {2}, sIndices[5], eIndices[5], sums[5];
int i, j, k, temp, sum, si, ei, pc = 1, longest = 0, count = 0;
for (i = 3; i < 100; i += 2) {
if (isPrime(i)) primes[pc++] = i;
}
for (i = 0; i < pc; ++i) {
for (j = pc-1; j >= i; --j) {
temp = j - i + 1;
if (temp < longest) break;
sum = 0;
for (k = i; k <= j; ++k) sum += primes[k];
if (isPrime(sum)) {
if (temp > longest) {
longest = temp;
count = 0;
}
sIndices[count] = i;
eIndices[count] = j;
sums[count] = sum;
++count;
break;
}
}
}
printf("The longest sequence(s) of CalmoSoft primes having a length of %d is/are:\n\n", longest);
for (i = 0; i < count; ++i) {
si = sIndices[i];
ei = eIndices[i];
sum = sums[i];
for (j = si; j <= ei; ++j) printf("%d + ", primes[j]);
printf("\b\b= %d which is prime\n", sum);
if (i < count - 1) printf("\n");
}
return 0;
}</syntaxhighlight>
 
{{out}}
<pre>
The longest sequence(s) of CalmoSoft primes having a length of 21 is/are:
 
7 + 11 + 13 + 17 + 19 + 23 + 29 + 31 + 37 + 41 + 43 + 47 + 53 + 59 + 61 + 67 + 71 + 73 + 79 + 83 + 89 = 953 which is prime
</pre>
 
=={{header|BASIC}}==
Line 212 ⟶ 402:
Sleep</syntaxhighlight>
{{out}}
<pre>[ 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 889 ]
7 + 11 + 13 + 17 + 19 + 23 + 29 + 31 + 37 + 41 + 43 + 47 + 53 + 59 + 61 + 67 + 71 + 73 + 79 + 83 + 889 = 953 is prime number
The longest sequence of CalmoSoft primes = 21</pre>
 
Line 263 ⟶ 453:
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
=={{header|C}}==
{{libheader|GMP}}
Run time is 250 milliseconds (GCC -O1) which is slightly slower than Go.
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stdint.h>
#include <locale.h>
#include <gmp.h>
 
#define MAX 50000000
 
typedef uint64_t u64;
 
int *primeSieve(int limit, int *length) {
int i, p, *primes;
int j, pc = 0;
limit++;
// True denotes composite, false denotes prime.
bool *c = calloc(limit, sizeof(bool)); // all false by default
c[0] = true;
c[1] = true;
for (i = 4; i < limit; i += 2) c[i] = true;
p = 3; // Start from 3.
while (true) {
u64 p2 = p * p;
if (p2 >= limit) break;
for (i = p2; i < limit; i += 2 * p) c[i] = true;
while (true) {
p += 2;
if (!c[p]) break;
}
}
for (i = 0; i < limit; ++i) {
if (!c[i]) ++pc;
}
primes = (int *)malloc(pc * sizeof(u64));
for (i = 0, j = 0; i < limit; ++i) {
if (!c[i]) primes[j++] = i;
}
free(c);
*length = pc;
return primes;
}
 
int calmoPrimes(int limit, int *primes, int len, int *sIndices, int *eIndices, u64 *sums, int *ilen) {
int i, j, temp, pc = len, longest = 0, ic = 0;
bool isEven;
u64 sum = 0, sum2;
mpz_t bsum;
mpz_init(bsum);
if (limit < MAX) {
for (i = 0; i < len; ++i) {
if (primes[i] > limit) {
pc = i;
break;
}
}
}
for (i = 0; i < pc; ++i) sum += primes[i];
for (i = 0; i < pc; ++i) {
if (pc - i < longest) break;
if (i > 0) sum -= primes[i-1];
isEven = i == 0;
sum2 = sum;
for (j = pc - 1; j >= i; --j) {
temp = j - i + 1;
if (temp < longest) break;
if (j < pc - 1) sum2 -= primes[j+1];
if ((temp % 2) == 0 != isEven) continue;
mpz_set_ui(bsum, sum2);
if (mpz_probab_prime_p(bsum, 5) > 0) {
if (temp > longest) {
longest = temp;
ic = 0;
}
sIndices[ic] = i;
eIndices[ic] = j;
sums[ic] = sum2;
++ic;
break;
}
}
}
*ilen = ic;
return longest;
}
 
int main() {
int i, j, k, len, ilen, limit, longest;
int *primes = primeSieve(MAX, &len);
int limits[6] = {100, 250, 5000, 10000, 500000, 50000000};
setlocale(LC_NUMERIC, "");
int sIndices[5];
int eIndices[5];
u64 sums[5];
for (i = 0; i < 6; ++i) {
limit = limits[i];
longest = calmoPrimes(limit, primes, len, sIndices, eIndices, sums, &ilen);
printf("For primes up to %'d the longest sequence(s) of CalmoSoft primes\n", limit);
printf("having a length of %'d is/are:\n\n", longest);
for (j = 0; j < ilen; ++j) {
char cps[130] = "";
char buf[20];
int bytes = 0, totalBytes = 0;
for (k = sIndices[j]; k <= sIndices[j]+5; ++k) {
bytes = sprintf(buf, "%d + ", primes[k]);
strcpy(cps + totalBytes, buf);
totalBytes += bytes;
}
strcpy(cps + totalBytes, ".. + ");
totalBytes += 5;
for (k = eIndices[j]-5; k <= eIndices[j]; ++k) {
bytes = sprintf(buf, "%d + ", primes[k]);
strcpy(cps + totalBytes, buf);
totalBytes += bytes;
}
cps[totalBytes-3] = '\0';
printf("%s = %'ld\n", cps, sums[j]);
}
printf("\n");
}
free(primes);
return 0;
}</syntaxhighlight>
 
{{out}}
<pre>
For primes up to 100 the longest sequence(s) of CalmoSoft primes
having a length of 21 is/are:
 
7 + 11 + 13 + 17 + 19 + 23 + .. + 67 + 71 + 73 + 79 + 83 + 89 = 953
 
For primes up to 250 the longest sequence(s) of CalmoSoft primes
having a length of 49 is/are:
 
11 + 13 + 17 + 19 + 23 + 29 + .. + 223 + 227 + 229 + 233 + 239 + 241 = 5,813
 
For primes up to 5,000 the longest sequence(s) of CalmoSoft primes
having a length of 665 is/are:
 
7 + 11 + 13 + 17 + 19 + 23 + .. + 4957 + 4967 + 4969 + 4973 + 4987 + 4993 = 1,543,127
 
For primes up to 10,000 the longest sequence(s) of CalmoSoft primes
having a length of 1,223 is/are:
 
3 + 5 + 7 + 11 + 13 + 17 + .. + 9883 + 9887 + 9901 + 9907 + 9923 + 9929 = 5,686,633
7 + 11 + 13 + 17 + 19 + 23 + .. + 9901 + 9907 + 9923 + 9929 + 9931 + 9941 = 5,706,497
 
For primes up to 500,000 the longest sequence(s) of CalmoSoft primes
having a length of 41,530 is/are:
 
2 + 3 + 5 + 7 + 11 + 13 + .. + 499787 + 499801 + 499819 + 499853 + 499879 + 499883 = 9,910,236,647
 
For primes up to 50,000,000 the longest sequence(s) of CalmoSoft primes
having a length of 3,001,117 is/are:
 
7 + 11 + 13 + 17 + 19 + 23 + .. + 49999699 + 49999711 + 49999739 + 49999751 + 49999753 + 49999757 = 72,618,848,632,313
</pre>
 
=={{header|C++}}==
{{trans|Phix}}
{{libheader|Primesieve}}
<syntaxhighlight lang="cpp">#include <chrono>
#include <iostream>
#include <locale>
#include <numeric>
#include <sstream>
 
#include <primesieve.hpp>
 
bool is_prime(uint64_t n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
if (n % 5 == 0)
return n == 5;
static constexpr uint64_t wheel[] = {4, 2, 4, 2, 4, 6, 2, 6};
uint64_t p = 7;
for (;;) {
for (uint64_t w : wheel) {
if (p * p > n)
return true;
if (n % p == 0)
return false;
p += w;
}
}
}
 
template <typename Iterator>
std::string join(Iterator begin, Iterator end, std::string_view separator) {
std::ostringstream os;
if (begin != end) {
os << *begin++;
for (; begin != end; ++begin)
os << separator << *begin;
}
return os.str();
}
 
int main() {
std::cout.imbue(std::locale(""));
auto start = std::chrono::high_resolution_clock::now();
std::vector<uint64_t> primes;
uint64_t from = 0;
for (uint64_t limit : {100, 5000, 10000, 500000, 50000000}) {
primesieve::generate_primes(from, limit, &primes);
from = limit + 1;
uint64_t sum =
std::accumulate(primes.begin(), primes.end(), uint64_t(0));
size_t last = primes.size();
size_t longest = 1;
std::vector<std::pair<size_t, uint64_t>> starts;
for (size_t start = 0; start <= last - longest; ++start) {
uint64_t s = sum;
for (size_t finish = last; finish-- >= start + longest;) {
if (is_prime(s)) {
size_t length = finish - start + 1;
if (length > longest) {
longest = length;
starts.clear();
}
starts.emplace_back(start, s);
}
s -= primes[finish];
}
sum -= primes[start];
}
std::cout << "For primes up to " << limit << ":\n"
<< "The following sequence" << (starts.size() == 1 ? "" : "s")
<< " of " << longest << " consecutive primes yield"
<< (starts.size() == 1 ? "s" : "") << " a prime sum:\n";
for (auto [start, sum] : starts) {
auto begin = primes.begin() + start;
auto end = begin + longest;
const char* separator = " + ";
if (longest > 12) {
std::cout << join(begin, begin + 6, separator) << separator
<< "..." << separator
<< join(end - 6, end, separator);
} else {
std::cout << join(begin, end, separator);
}
std::cout << " = " << sum << '\n';
}
std::cout << '\n';
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration(end - start);
std::cout << "Elapsed time: " << duration.count() << " seconds\n";
}</syntaxhighlight>
 
{{out}}
<pre>
For primes up to 100:
The following sequence of 21 consecutive primes yields a prime sum:
7 + 11 + 13 + 17 + 19 + 23 + ... + 67 + 71 + 73 + 79 + 83 + 89 = 953
 
For primes up to 5,000:
The following sequence of 665 consecutive primes yields a prime sum:
7 + 11 + 13 + 17 + 19 + 23 + ... + 4957 + 4967 + 4969 + 4973 + 4987 + 4993 = 1,543,127
 
For primes up to 10,000:
The following sequences of 1,223 consecutive primes yield a prime sum:
3 + 5 + 7 + 11 + 13 + 17 + ... + 9883 + 9887 + 9901 + 9907 + 9923 + 9929 = 5,686,633
7 + 11 + 13 + 17 + 19 + 23 + ... + 9901 + 9907 + 9923 + 9929 + 9931 + 9941 = 5,706,497
 
For primes up to 500,000:
The following sequence of 41,530 consecutive primes yields a prime sum:
2 + 3 + 5 + 7 + 11 + 13 + ... + 499787 + 499801 + 499819 + 499853 + 499879 + 499883 = 9,910,236,647
 
For primes up to 50,000,000:
The following sequence of 3,001,117 consecutive primes yields a prime sum:
7 + 11 + 13 + 17 + 19 + 23 + ... + 49999699 + 49999711 + 49999739 + 49999751 + 49999753 + 49999757 = 72,618,848,632,313
 
Elapsed time: 0.0814633 seconds
</pre>
 
=={{header|Go}}==
Line 271 ⟶ 744:
import (
"fmt"
"math/big"
"rcu"
"strconvtime"
)
 
var start = time.Now()
func main() {
 
primes := rcu.Primes(100)
const max = 50_000_000
pc := len(primes)
 
var primes = rcu.Primes(max)
 
func calmoPrimes(limit int) (int, []int, []int, []int) {
var pc, sum int
if limit < max {
for i := 0; i < len(primes); i++ {
if primes[i] > limit {
pc = i
break
}
}
} else {
pc = len(primes)
}
for i := 0; i < pc; i++ {
sum += primes[i]
}
longest := 0
var sIndices, eIndices, sums []int
for i := 0; i < pc; i++ {
if pc-i < longest {
break
}
if i > 0 {
sum -= primes[i-1]
}
isEven := i == 0
sum2 := sum
for j := pc - 1; j >= i; j-- {
temp := j - i + 1
Line 286 ⟶ 786:
break
}
sumif :=j rcu.SumInts(primes[i< : j+pc-1]) {
if rcu.IsPrime(sum) { sum2 -= primes[j+1]
}
if (temp % 2) == 0 != isEven {
continue
}
bsum := big.NewInt(int64(sum2))
if bsum.ProbablyPrime(5) {
if temp > longest {
longest = temp
sIndices = []int{i}
eIndices = []int{j}
sums = []int{sum2}
} else {
sIndices = append(sIndices, i)
eIndices = append(eIndices, j)
sums = append(sums, sum2)
}
break
Line 300 ⟶ 808:
}
}
return longest, sIndices, eIndices, sums
fmt.Println("The longest sequence(s) of CalmoSoft primes having a length of", longest, "is/are:\n")
}
for i := 0; i < len(sIndices); i++ {
 
cp := primes[sIndices[i] : eIndices[i]+1]
func main() {
sum := rcu.SumInts(cp)
for _, limit := range []int{100, 250, 5000, 10000, 500000, 50000000} {
cps := ""
forlongest, isIndices, eIndices, sums := 0; i < lencalmoPrimes(cplimit); i++ {
fmt.Println("For primes up to", rcu.Commatize(limit), "the longest sequence(s) of CalmoSoft primes")
cps += strconv.Itoa(cp[i])
fmt.Println("having a length of", rcu.Commatize(longest), "is/are:\n")
if i < len(cp)-1 {
for i := 0; i < len(sIndices); cps i+= " + "{
cp1 := primes[sIndices[i] : sIndices[i]+6]
cp2 := primes[eIndices[i]-5 : eIndices[i]+1]
cps := ""
for _, p := range cp1 {
cps += fmt.Sprintf("%d + ", p)
}
cps += ".. + "
for _, p := range cp2 {
cps += fmt.Sprintf("%d + ", p)
}
fmt.Printf("%s = %s\n", cps[:len(cps)-3], rcu.Commatize(sums[i]))
}
fmt.Println()
cps += " = " + strconv.Itoa(sum) + " which is prime"
}
fmt.Println(cps)
fmt.Printf("Took %d ms\n", time.Since(start).Milliseconds())
if i < len(sIndices)-1 {
}</syntaxhighlight>
fmt.Println()
 
{{out}}
<pre>
For primes up to 100 the longest sequence(s) of CalmoSoft primes
having a length of 21 is/are:
 
7 + 11 + 13 + 17 + 19 + 23 + .. + 67 + 71 + 73 + 79 + 83 + 89 = 953
 
For primes up to 250 the longest sequence(s) of CalmoSoft primes
having a length of 49 is/are:
 
11 + 13 + 17 + 19 + 23 + 29 + .. + 223 + 227 + 229 + 233 + 239 + 241 = 5,813
 
For primes up to 5,000 the longest sequence(s) of CalmoSoft primes
having a length of 665 is/are:
 
7 + 11 + 13 + 17 + 19 + 23 + .. + 4957 + 4967 + 4969 + 4973 + 4987 + 4993 = 1,543,127
 
For primes up to 10,000 the longest sequence(s) of CalmoSoft primes
having a length of 1,223 is/are:
 
3 + 5 + 7 + 11 + 13 + 17 + .. + 9883 + 9887 + 9901 + 9907 + 9923 + 9929 = 5,686,633
7 + 11 + 13 + 17 + 19 + 23 + .. + 9901 + 9907 + 9923 + 9929 + 9931 + 9941 = 5,706,497
 
For primes up to 500,000 the longest sequence(s) of CalmoSoft primes
having a length of 41,530 is/are:
 
2 + 3 + 5 + 7 + 11 + 13 + .. + 499787 + 499801 + 499819 + 499853 + 499879 + 499883 = 9,910,236,647
 
For primes up to 50,000,000 the longest sequence(s) of CalmoSoft primes
having a length of 3,001,117 is/are:
 
7 + 11 + 13 + 17 + 19 + 23 + .. + 49999699 + 49999711 + 49999739 + 49999751 + 49999753 + 49999757 = 72,618,848,632,313
 
Took 210 ms
</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
 
 
type TLongInfo = record
RangeStart,RangeStop: integer;
SeqStart,SeqStop: integer;
Count,Sum: integer;
end;
 
procedure CalmoSoftPrimes(Memo: TMemo);
{Find longest sequence of prime numbers that adds up to a prime}
var Sieve: TPrimeSieve;
var Best,Tmp: TLongInfo;
var I,Cnt: integer;
var S: string;
 
function GetLongest(N,Limit: integer): TLongInfo;
{Get longest sequence starting at N}
{Find longest sequence of primes whose sum is prime}
var Next,Sum,Cnt: integer;
begin
Result.Count:=1;
Result.SeqStart:=N;
Result.SeqStop:=N;
Result.Sum:=1;
Sum:=N; Next:=N;
Cnt:=1;
while true do
begin
Next:=Sieve.NextPrime(Next);
if Next>Limit then break;
Sum:=Sum+Next;
Inc(Cnt);
if IsPrime(Sum) then
begin
Result.SeqStop:=Next;
Result.Count:=Cnt;
Result.Sum:=Sum;
end;
end;
end;
 
 
function LongestRange(Start,Limit: integer): TLongInfo;
{Find longest sequence between Start and Limit}
{Start should be a prime number}
var I: integer;
begin
I:=Start;
Result.SeqStart:=0;
Result.SeqStop:=0;
Result.Count:=0;
while I<=Limit do
begin
Tmp:=GetLongest(I,Limit);
if Tmp.Count>Result.Count then Result:=Tmp;
I:=Sieve.NextPrime(I);
end;
Result.RangeStart:=Start;
Result.RangeStop:=Limit;
end;
 
 
procedure ShowSequenceHeader(Best: TLongInfo);
{Show summary of information}
begin
Memo.Lines.Add('Range: '+IntToStr(Best.RangeStart)+' '+IntToStr(Best.RangeStop));
Memo.Lines.Add('Longest Sequence: '+IntToStr(Best.Count));
Memo.Lines.Add('Sum: '+IntToStr(Best.Sum));
end;
 
 
 
procedure ShowSequence(Best: TLongInfo; Start,Limit: integer);
{Extract sequence info from best and display it}
var S: string;
var I,Cnt: integer;
begin
S:=''; Cnt:=0;
{if Start=0 display full range other wise}
{display from start to limit}
if Start=0 then I:=Best.SeqStart
else I:=Start;
while I<=Best.SeqStop do
begin
Inc(Cnt);
S:=S+Format('%5d',[I]);
if (Cnt mod 10)=0 then S:=S+CRLF;
if Cnt>=Limit then break;
I:=Sieve.NextPrime(I);
end;
Memo.Lines.Add(S);
end;
 
 
procedure ShowHeaderSequence(Best: TLongInfo);
{Show header and sequence}
begin
ShowSequenceHeader(Best);
ShowSequence(Best,0,high(integer));
end;
 
 
 
begin
Sieve:=TPrimeSieve.Create;
try
{Create enough primes to cover range}
Sieve.Intialize(1000);
{Find longest sequence in range}
Best:=LongestRange(2,100);
ShowHeaderSequence(Best);
finally Sieve.Free; end;
end;
 
 
</syntaxhighlight>
{{out}}
<pre>
Range: 2 100
Longest Sequence: 21
Sum: 953
7 11 13 17 19 23 29 31 37 41
43 47 53 59 61 67 71 73 79 83
89
Elapsed Time: 2.277 ms.
 
</pre>
 
 
=={{header|J}}==
 
It would be useful to find the length of the longest sequence of these primes where the sum is prime:
 
<syntaxhighlight lang=J> >./,(+/\\. 99#1)*1 p: +/\\. p:i.99
96</syntaxhighlight>
 
With this, we can check all sums of subsequences of 96 primes (from the first 99 primes) for primality:
 
<syntaxhighlight lang=J> 1 p: 96+/\p:i.99
1 0 0 0</syntaxhighlight>
 
In other words, the sum of these primes
 
<syntaxhighlight lang=J> p:i.8 12
2 3 5 7 11 13 17 19 23 29 31 37
41 43 47 53 59 61 67 71 73 79 83 89
97 101 103 107 109 113 127 131 137 139 149 151
157 163 167 173 179 181 191 193 197 199 211 223
227 229 233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349 353 359
367 373 379 383 389 397 401 409 419 421 431 433
439 443 449 457 461 463 467 479 487 491 499 503</syntaxhighlight>
 
is this prime:
 
<syntaxhighlight lang=J> +/p:i.96
22039</syntaxhighlight>
 
=={{header|Java}}==
{{trans|Phix}}
Uses the PrimeGenerator class from [[Extensible prime generator#Java]].
<syntaxhighlight lang="java">import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
 
public class CalmoSoftPrimes {
public static void main(String[] args) {
PrimeGenerator primeGen = new PrimeGenerator(100000, 250000);
List<Integer> primes = new ArrayList<>();
final int[] limits = {100, 5000, 10000, 500000, 50000000};
long total = 0;
int last = 0;
int prime = primeGen.nextPrime();
for (int limit : limits) {
do {
primes.add(prime);
total += prime;
++last;
prime = primeGen.nextPrime();
} while (prime < limit);
long sum = total;
int longest = 1;
List<Integer> starts = new ArrayList<>();
for (int start = 0; start <= last - longest; ++start) {
long s = sum;
for (int finish = last; finish-- >= start + longest;) {
if (isPrime(s)) {
int length = finish - start + 1;
if (length > longest) {
longest = length;
starts.clear();
}
starts.add(start);
}
s -= primes.get(finish);
}
sum -= primes.get(start);
}
System.out.printf("For primes up to %d:\nThe following sequence%s of %d consecutive primes yield%s a prime sum:\n",
limit, starts.size() == 1 ? "" : "s", longest, starts.size() == 1 ? "s" : "");
for (int i = 0; i < starts.size(); ++i) {
int start = starts.get(i);
sum = 0;
for (int j = start; j < start + longest; ++j)
sum += primes.get(j);
final String separator = " + ";
if (longest > 12) {
System.out.print(join(separator, primes.subList(start, start + 6))
+ separator + "..." + separator
+ join(separator, primes.subList(start + longest - 6, start + longest)));
} else {
System.out.print(join(separator, primes.subList(start, start + longest)));
}
System.out.println(" = " + sum);
}
System.out.println();
}
}
 
private static <T> String join(String separator, List<T> list) {
return list.stream().map(Object::toString).collect(Collectors.joining(separator));
}
 
private static boolean isPrime(long n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (long p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
}</syntaxhighlight>
Line 321 ⟶ 1,120:
{{out}}
<pre>
For primes up to 100:
The longest sequence(s) of CalmoSoft primes having a length of 21 is/are:
The following sequence of 21 consecutive primes yields a prime sum:
7 + 11 + 13 + 17 + 19 + 23 + ... + 67 + 71 + 73 + 79 + 83 + 89 = 953
 
For primes up to 5000:
The following sequence of 665 consecutive primes yields a prime sum:
7 + 11 + 13 + 17 + 19 + 23 + ... + 4957 + 4967 + 4969 + 4973 + 4987 + 4993 = 1543127
 
For primes up to 10000:
The following sequences of 1223 consecutive primes yield a prime sum:
3 + 5 + 7 + 11 + 13 + 17 + ... + 9883 + 9887 + 9901 + 9907 + 9923 + 9929 = 5686633
7 + 11 + 13 + 17 + 19 + 23 + ... + 9901 + 9907 + 9923 + 9929 + 9931 + 9941 = 5706497
 
For primes up to 500000:
The following sequence of 41530 consecutive primes yields a prime sum:
2 + 3 + 5 + 7 + 11 + 13 + ... + 499787 + 499801 + 499819 + 499853 + 499879 + 499883 = 9910236647
 
For primes up to 50000000:
The following sequence of 3001117 consecutive primes yields a prime sum:
7 + 11 + 13 + 17 + 19 + 23 + ... + 49999699 + 49999711 + 49999739 + 49999751 + 49999753 + 49999757 = 72618848632313
 
7 + 11 + 13 + 17 + 19 + 23 + 29 + 31 + 37 + 41 + 43 + 47 + 53 + 59 + 61 + 67 + 71 + 73 + 79 + 83 + 89 = 953 which is prime
</pre>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">using Primes
 
function calmo_prime_sequence(N)
pri = primes(N)
for w in lastindex(pri):-1:2
psum = sum(pri[1:w])
for d in 0:lastindex(pri)-w
if d > 0
psum -= pri[d]
psum += pri[w + d]
end
if isprime(psum)
println("Longest Calmo prime seq (length ", w,
") of primes less than $N totals ", sum(pri[begin+d:d+w]))
if w > 24
println(string(pri[d+1:d+6])[begin:end-1], ", ... ",
string(pri[d-5+w:d+w])[begin+1:end], "\n")
else
println("The sequence is: ", pri[d+1:d+w], "\n")
end
return
end
end
end
end
 
foreach(calmo_prime_sequence, [100, 500_000, 50_000_000])
</syntaxhighlight>{{out}}
<pre>
Longest Calmo prime seq (length 21) of primes less than 100 totals 953
The sequence is: [7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89]
 
Longest Calmo prime seq (length 41530) of primes less than 500000 totals 9910236647
[2, 3, 5, 7, 11, 13, ... 499787, 499801, 499819, 499853, 499879, 499883]
 
Longest Calmo prime seq (length 3001117) of primes less than 50000000 totals 72618848632313
[7, 11, 13, 17, 19, 23, ... 49999699, 49999711, 49999739, 49999751, 49999753, 49999757]
</pre>
 
=={{header|Nim}}==
{{trans|Wren}}
With some modifications.
<syntaxhighlight lang="Nim">import std/[algorithm, math, strformat, strutils]
 
func initPrimes(lim: Natural): seq[int] =
## Build list of primes using a sieve of Erathostenes.
var composite = newSeq[bool]((lim + 1) shr 1)
composite[0] = true
for n in countup(3, int(sqrt(lim.toFloat)), 2):
if not composite[n shr 1]:
for k in countup(n * n, lim, 2 * n):
composite[k shr 1] = true
result.add 2
for n in countup(3, lim, 2):
if not composite[n shr 1]:
result.add n
 
func isPrime(n: Natural): bool =
## Return "true" is "n" is prime.
if n < 2: return false
if (n and 1) == 0: return n == 2
if n mod 3 == 0: return n == 3
var d = 5
var step = 2
while d * d <= n:
if n mod d == 0:
return false
inc d, step
step = 6 - step
return true
 
const Max = 50_000_000
let primes = initPrimes(Max)
 
proc calmoPrimes(limit: Positive): (int, seq[int], seq[int], seq[int]) =
## Find the longest sequence of CalmoSoft primes up to "limit".
let phigh = primes.upperBound(limit) - 1
var sum1 = sum(primes.toOpenArray(0, phigh))
var longest = 0
var sIndices, eIndices, sums: seq[int]
for i in 0..phigh:
if phigh - i + 1 < longest:
break
if i > 0:
dec sum1, primes[i - 1]
let isEven = i == 0
var sum2 = sum1
for j in countdown(phigh, i):
let temp = j - i + 1
if temp < longest:
break
if j < phigh:
dec sum2, primes[j + 1]
if ((temp and 1) == 0) != isEven:
continue
if sum2.isPrime:
if temp > longest:
longest = temp
sIndices = @[i]
eIndices = @[j]
sums = @[sum2]
else:
sIndices.add i
eIndices.add j
sums.add sum2
break
result = (longest, sIndices, eIndices, sums)
 
func plural(lg: int): (string, string) =
## Return the singular or plural form according to value of "lg".
result = if lg == 1: ("", "is") else: ("s", "are")
 
 
for limit in [100, 250, 5000, 10000, 500000, 50000000]:
let (longest, sIndices, eIndices, sums) = calmoPrimes(limit)
let (p1, p2) = plural(sums.len)
echo &"For primes up to {insertSep($limit)} the longest sequence{p1} of CalmoSoft primes"
echo &"having a length of {insertSep($longest)} {p2}:\n"
for i in 0..sIndices.high:
let cp = primes[sIndices[i]..eIndices[i]]
echo &"{cp[0..5].join(\" + \")} + ... + {cp[^6..^1].join(\" + \")} = {sums[i]}"
echo()
</syntaxhighlight>
 
{{out}}
<pre>For primes up to 100 the longest sequence of CalmoSoft primes
having a length of 21 is:
 
7 + 11 + 13 + 17 + 19 + 23 + ... + 67 + 71 + 73 + 79 + 83 + 89 = 953
 
For primes up to 250 the longest sequence of CalmoSoft primes
having a length of 49 is:
 
11 + 13 + 17 + 19 + 23 + 29 + ... + 223 + 227 + 229 + 233 + 239 + 241 = 5813
 
For primes up to 5_000 the longest sequence of CalmoSoft primes
having a length of 665 is:
 
7 + 11 + 13 + 17 + 19 + 23 + ... + 4957 + 4967 + 4969 + 4973 + 4987 + 4993 = 1543127
 
For primes up to 10_000 the longest sequences of CalmoSoft primes
having a length of 1_223 are:
 
3 + 5 + 7 + 11 + 13 + 17 + ... + 9883 + 9887 + 9901 + 9907 + 9923 + 9929 = 5686633
 
7 + 11 + 13 + 17 + 19 + 23 + ... + 9901 + 9907 + 9923 + 9929 + 9931 + 9941 = 5706497
 
For primes up to 500_000 the longest sequence of CalmoSoft primes
having a length of 41_530 is:
 
2 + 3 + 5 + 7 + 11 + 13 + ... + 499787 + 499801 + 499819 + 499853 + 499879 + 499883 = 9910236647
 
For primes up to 50_000_000 the longest sequence of CalmoSoft primes
having a length of 3_001_117 is:
 
7 + 11 + 13 + 17 + 19 + 23 + ... + 49999699 + 49999711 + 49999739 + 49999751 + 49999753 + 49999757 = 72618848632313
</pre>
 
=={{header|Perl}}==
{{libheader|ntheory}}
<syntaxhighlight lang="perl" line>use strict;
use warnings;
use ntheory <primes is_prime vecsum>;
 
for my $limit (<100 250 500 1000>) {
my @primes = @{ primes(2,$limit) };
T: for my $terms (reverse 1 .. @primes) {
for my $i (0 .. @primes-$terms) {
my @primes = @primes[$i..($i+$terms)-1];
next unless is_prime (my $sum = vecsum @primes);
print "For primes up to $limit:\n",
join ' ... ', join(' + ',@primes[0..5]), join(' + ',@primes[-5..-1]) . " = $sum ($terms primes)\n\n";
last T
}
}
}</syntaxhighlight>
{{out}}
<pre>For primes up to 100:
7 + 11 + 13 + 17 + 19 + 23 ... 71 + 73 + 79 + 83 + 89 = 953 (21 primes)
 
For primes up to 250:
11 + 13 + 17 + 19 + 23 + 29 ... 227 + 229 + 233 + 239 + 241 = 5813 (49 primes)
 
For primes up to 500:
31 + 37 + 41 + 43 + 47 + 53 ... 467 + 479 + 487 + 491 + 499 = 21407 (85 primes)
 
For primes up to 1000:
13 + 17 + 19 + 23 + 29 + 31 ... 971 + 977 + 983 + 991 + 997 = 76099 (163 primes)</pre>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
{{incomplete|Phix}}
<span style="color: #008080;">for</span> <span style="color: #000000;">lim</span> <span style="color: #008080;">in</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">100</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5e3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1e4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5e5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5e7</span><span style="color: #0000FF;">}</span> <span style="color: #008080;">do</span>
I'll give you guys a chance to figure out the stretch goal on your own...
<span style="color: #004080;">sequence</span> <span style="color: #000000;">primes</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_primes_le</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lim</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">starts</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">primes</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">longest</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">start</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">primes</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">start</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">l</span><span style="color: #0000FF;">-</span><span style="color: #000000;">longest</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">t</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">finish</span><span style="color: #0000FF;">=</span><span style="color: #000000;">l</span> <span style="color: #008080;">to</span> <span style="color: #000000;">start</span><span style="color: #0000FF;">+</span><span style="color: #000000;">longest</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">by</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">is_prime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">len</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">finish</span><span style="color: #0000FF;">-</span><span style="color: #000000;">start</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">len</span><span style="color: #0000FF;">></span><span style="color: #000000;">longest</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">longest</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">len</span>
<span style="color: #000000;">starts</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">start</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">else</span>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">len</span><span style="color: #0000FF;">==</span><span style="color: #000000;">longest</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">starts</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">start</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">primes</span><span style="color: #0000FF;">[</span><span style="color: #000000;">finish</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">t</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">primes</span><span style="color: #0000FF;">[</span><span style="color: #000000;">start</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">start</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</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;">"For primes up to %s:\n"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">ordinal</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lim</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">))</span>
<span style="color: #004080;">string</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ns</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">starts</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">?{</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"s"</span><span style="color: #0000FF;">}:{</span><span style="color: #008000;">"s"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</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;">"The following sequence%s of %,d consecutive primes yield%s a prime sum:\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">longest</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ns</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">start</span> <span style="color: #008080;">in</span> <span style="color: #000000;">starts</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">p</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">primes</span><span style="color: #0000FF;">[</span><span style="color: #000000;">start</span><span style="color: #0000FF;">..</span><span style="color: #000000;">start</span><span style="color: #0000FF;">+</span><span style="color: #000000;">longest</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">f6</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">6</span><span style="color: #0000FF;">],</span><span style="color: #008000;">" + "</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">:=</span><span style="color: #008000;">"%d"</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">l6</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">[-</span><span style="color: #000000;">6</span><span style="color: #0000FF;">..-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],</span><span style="color: #008000;">" + "</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">:=</span><span style="color: #008000;">"%d"</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;">" %s +..+ %s = %,d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">f6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">l6</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</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;">"\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 366 ⟶ 1,407:
Longest Calmo prime seq (length 21) of primes less than 100 is:
[7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89]
</pre>
=== Stretch task ===
{{trans|Julia}}
<syntaxhighlight lang="python">""" rosettacode.org/wiki/CalmoSoft_primes """
 
from sympy import isprime, primerange
 
 
def calmo_prime_sequence(maxp):
""" find the largest prime seq in primes < maxp that sums to a prime """
pri = list(primerange(maxp))
for win in range(len(pri)-1, 1, -1): # window size
psum = sum(pri[:win])
for bot in range(-1, len(pri)-win): # the last bottom of window
if bot >= 0:
psum -= pri[bot]
psum += pri[win + bot]
if isprime(psum):
print('Longest Calmo prime seq (length', win,
') of primes less than', maxp, 'totals', sum(pri[bot+1:bot+win+1]))
if win > 24:
print('[', ', '.join(map(str, pri[bot+1:bot+7])), ', ... ',
', '.join(map(str, pri[bot-5+win:bot+win+1])), ']\n', sep='')
else:
print('The sequence is:', pri[bot+1:bot+win+1], '\n')
return
 
 
for pmax in [100, 500_000, 50_000_000]:
calmo_prime_sequence(pmax)
</syntaxhighlight>{{out}}
<pre>
Longest Calmo prime seq (length 21 ) of primes less than 100 totals 953
The sequence is: [7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89]
 
Longest Calmo prime seq (length 41530 ) of primes less than 500000 totals 9910236647
[2, 3, 5, 7, 11, 13, ... 499787, 499801, 499819, 499853, 499879, 499883]
 
Longest Calmo prime seq (length 3001117 ) of primes less than 50000000 totals 72618848632313
[7, 11, 13, 17, 19, 23, ... 49999699, 49999711, 49999739, 49999751, 49999753, 49999757]
</pre>
 
=={{header|Raku}}==
{{incorrect|Raku|see talk page}}
Longest sliding window prime sums
 
<syntaxhighlight lang="raku" line>use Lingua::EN::Numbers;
 
sub sliding-window(@list, $window) { (^(+@list - $window)).map: { @list[$_ ..^ $_+$window] } }
 
for flat (1e2, 1e3, 1e4, 1e5).map: { (1, 2.5, 5) »×» $_ } -> $upto {
Line 383 ⟶ 1,463:
my @sums = @primes.&sliding-window($_).grep: { .sum.is-prime }
next unless @sums;
say "\nFor primes up to {$upto.Int.&cardinal}:\nLongest sequence of consecutive primes yielding a prime sum: elements: {comma 1+$_}";
for @sums { say " {join '...', .[0..5, *-5..*]».&comma».join(' + ')}, sum: {.sum.&comma}" }
last
Line 394 ⟶ 1,474:
 
For primes up to two hundred fifty:
Longest sequence of consecutive primes yielding a prime sum: elements: 4749
7 + 11 + 13 + 17 + 19 + 23 + 29...199227 + 211229 + 223233 + 227239 + 229241, sum: 5,107813
11 + 13 + 17 + 19 + 23 + 29...211 + 223 + 227 + 229 + 233, sum: 5,333
 
For primes up to five hundred:
Longest sequence of consecutive primes yielding a prime sum: elements: 8185
1131 + 1337 + 1741 + 1943 + 2347 + 2953...419467 + 421479 + 431487 + 433491 + 439499, sum: 1621,823407
19 + 23 + 29 + 31 + 37 + 41...433 + 439 + 443 + 449 + 457, sum: 18,131
29 + 31 + 37 + 41 + 43 + 47...443 + 449 + 457 + 461 + 463, sum: 19,013
 
For primes up to one thousand:
Longest sequence of consecutive primes yielding a prime sum: elements: 162163
213 + 317 + 519 + 723 + 1129 + 1331...929971 + 937977 + 941983 + 947991 + 953997, sum: 7076,241099
 
For primes up to two thousand, five hundred:
Line 422 ⟶ 1,499:
 
For primes up to twenty-five thousand:
Longest sequence of consecutive primes yielding a prime sum: elements: 2,757759
37 + 511 + 713 + 1117 + 1319 + 1723...24,919967 + 24,923971 + 24,943977 + 24,953979 + 24,967989, sum: 32,305405,799707
 
For primes up to fifty thousand:
Longest sequence of consecutive primes yielding a prime sum: elements: 5,125131
135 + 177 + 1911 + 2313 + 2917 + 3119...49,927943 + 49,937957 + 49,939991 + 49,943993 + 49,957999, sum: 120121,863013,297303
 
For primes up to one hundred thousand:
Line 434 ⟶ 1,511:
 
For primes up to two hundred fifty thousand:
Longest sequence of consecutive primes yielding a prime sum: elements: 22,037041
5 + 7 + 11 + 13 + 17 + 19 + 23...249,871947 + 249,881967 + 249,911971 + 249,923973 + 249,943989, sum: 2,621623,781031,299141
 
For primes up to five hundred thousand:
Line 515 ⟶ 1,592:
=={{header|Wren}}==
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="ecmascript">import "./math" for Int, Nums
This runs in about 3.5 seconds (cf. Julia 1.3 seconds) on my Core i7 machine. However, 2.6 seconds of that is needed to sieve for primes up to 50 million.
<syntaxhighlight lang="wren">import "./math" for Int, Nums
import "./fmt"for Fmt
 
var primesmax = Int.primeSieve(100)50000000
var pcprimes = primesInt.countprimeSieve(max)
 
var longest = 0
var sIndicescalmoPrimes = []Fn.new { |limit|
var pc = (limit < max) ? primes.count { |p| p <= limit } : primes.count
var eIndices = []
var sum = (limit < max) ? Nums.sum(primes.take(pc)) : Nums.sum(primes)
for (i in 0...pc) {
forvar (jlongest in= pc-1..i) {0
var tempsIndices = j - i + 1[]
var eIndices = []
if (temp < longest) break
var sumsums = Nums.sum(primes[i..j])
for (i in if (Int0.isPrime(sum)..pc) {
if (pc - i if (temp >< longest) {break
if (i > 0) sum = sum - longest = tempprimes[i-1]
var isEven = sIndices(i == [i]0)
var eIndicessum2 = [j]sum
for (j in } elsepc-1..i) {
var temp = j - sIndices.add(i) + 1
if (temp < eIndices.add(jlongest) break
if (j < pc - 1) sum2 = sum2 - primes[j+1]
if ((temp % 2) == 0 != isEven) continue
if (Int.isPrime2(sum2)) {
if (temp > longest) {
longest = temp
sIndices = [i]
eIndices = [j]
sums = [sum2]
} else {
sIndices.add(i)
eIndices.add(j)
sums.add(sum2)
}
break
}
break
}
}
return [longest, sIndices, eIndices, sums]
}
 
System.print("The longest sequence(s) of CalmoSoft primes having a length of %(longest) is/are:\n")
for (ilimit in 0...sIndices.count[100, 250, 5000, 10000, 500000, 50000000]) {
var cpres = primes[sIndices[i]calmoPrimes..eIndices[i]]call(limit)
var sumlongest = Nums.sum(cp)res[0]
var sIndices = res[1]
var cps = cp.join(" + ") + " = " + sum.toString + " which is prime"
var eIndices = res[2]
System.print(cps)
var sums = res[3]
if (i < sIndices.count - 1) System.print()
Fmt.print("For primes up to $,d the longest sequence(s) of CalmoSoft primes", limit)
Fmt.print("having a length of $,d is/are:\n", longest)
for (i in 0...sIndices.count) {
var cp = primes[sIndices[i]..eIndices[i]]
var cps = Fmt.va("d", 1, cp, 0, " + ", "", "", 6, "..")
Fmt.print("$s = $,d", cps, sums[i])
}
System.print()
}</syntaxhighlight>
 
{{out}}
<pre>
TheFor primes up to 100 the longest sequence(s) of CalmoSoft primes having a length of 21 is/are:
having a length of 21 is/are:
 
7 + 11 + 13 + 17 + 19 + 23 + .. + 67 + 71 + 73 + 79 + 83 + 89 = 953
 
For primes up to 250 the longest sequence(s) of CalmoSoft primes
having a length of 49 is/are:
 
11 + 13 + 17 + 19 + 23 + 29 + .. + 223 + 227 + 229 + 233 + 239 + 241 = 5,813
 
For primes up to 5,000 the longest sequence(s) of CalmoSoft primes
having a length of 665 is/are:
 
7 + 11 + 13 + 17 + 19 + 23 + .. + 4957 + 4967 + 4969 + 4973 + 4987 + 4993 = 1,543,127
 
For primes up to 10,000 the longest sequence(s) of CalmoSoft primes
having a length of 1,223 is/are:
 
3 + 5 + 7 + 11 + 13 + 17 + .. + 9883 + 9887 + 9901 + 9907 + 9923 + 9929 = 5,686,633
7 + 11 + 13 + 17 + 19 + 23 + .. + 9901 + 9907 + 9923 + 9929 + 9931 + 9941 = 5,706,497
 
For primes up to 500,000 the longest sequence(s) of CalmoSoft primes
having a length of 41,530 is/are:
 
2 + 3 + 5 + 7 + 11 + 13 + .. + 499787 + 499801 + 499819 + 499853 + 499879 + 499883 = 9,910,236,647
 
For primes up to 50,000,000 the longest sequence(s) of CalmoSoft primes
having a length of 3,001,117 is/are:
 
7 + 11 + 13 + 17 + 19 + 23 + 29.. + 3149999699 + 3749999711 + 4149999739 + 4349999751 + 4749999753 + 53 + 59 + 61 + 67 + 71 + 73 + 79 + 83 + 8949999757 = 953 which is prime72,618,848,632,313
</pre>
 
9,476

edits