Consecutive primes with ascending or descending differences: Difference between revisions

Added Easylang
m (added to Prime Numbers category.)
(Added Easylang)
 
(32 intermediate revisions by 21 users not shown)
Line 1:
{{Draft task|Prime Numbers}}
 
;Task:
Line 11:
 
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F primes_upto(limit)
V is_prime = [0B] * 2 [+] [1B] * (limit - 1)
L(n) 0 .< Int(limit ^ 0.5 + 1.5)
I is_prime[n]
L(i) (n * n .. limit).step(n)
is_prime[i] = 0B
R enumerate(is_prime).filter((i, prime) -> prime).map((i, prime) -> i)
 
V primelist = primes_upto(1'000'000)
 
V listlen = primelist.len
 
V pindex = 1
V old_diff = -1
V curr_list = [primelist[0]]
[Int] longest_list
 
L pindex < listlen
 
V diff = primelist[pindex] - primelist[pindex - 1]
I diff > old_diff
curr_list.append(primelist[pindex])
I curr_list.len > longest_list.len
longest_list = curr_list
E
curr_list = [primelist[pindex - 1], primelist[pindex]]
 
old_diff = diff
pindex++
 
print(longest_list)
 
pindex = 1
old_diff = -1
curr_list = [primelist[0]]
longest_list.drop()
 
L pindex < listlen
 
V diff = primelist[pindex] - primelist[pindex - 1]
I diff < old_diff
curr_list.append(primelist[pindex])
I curr_list.len > longest_list.len
longest_list = curr_list
E
curr_list = [primelist[pindex - 1], primelist[pindex]]
 
old_diff = diff
pindex++
 
print(longest_list)</syntaxhighlight>
 
{{out}}
<pre>
[128981, 128983, 128987, 128993, 129001, 129011, 129023, 129037]
[322171, 322193, 322213, 322229, 322237, 322243, 322247, 322249]
</pre>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">BEGIN # find sequences of primes where the gaps between the elements #
# are strictly ascending/descending #
# reurns a list of primes up to n #
Line 86 ⟶ 147:
show sequence( primes, "ascending", asc start, asc length );
show sequence( primes, "descending", desc start, desc length )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 98 ⟶ 159:
</pre>
 
=={{header|C#|CSharpBASIC}}==
==={{header|FreeBASIC}}===
Use any of the primality testing code on this site as an include; I won't reproduce it here.
<syntaxhighlight lang="freebasic">#define UPPER 1000000
#include"isprime.bas"
 
dim as uinteger champ = 0, record = 0, streak, i, j, n
 
'first generate all the primes below UPPER
redim as uinteger prime(1 to 2)
prime(1) = 2 : prime(2) = 3
for i = 5 to UPPER step 2
if isprime(i) then
redim preserve prime(1 to ubound(prime) + 1)
prime(ubound(prime)) = i
end if
next i
n = ubound(prime)
 
'now look for the longest streak of ascending primes
for i = 2 to n-1
j = i + 1
streak = 1
while j<=n andalso prime(j)-prime(j-1) > prime(j-1)-prime(j-2)
streak += 1
j+=1
wend
if streak > record then
champ = i-1
record = streak
end if
next i
 
print "The longest sequence of ascending primes (with their difference from the last one) is:"
for i = champ+1 to champ+record
print prime(i-1);" (";prime(i)-prime(i-1);") ";
next i
print prime(i-1) : print
'now for the descending ones
 
record = 0 : champ = 0
for i = 2 to n-1
j = i + 1
streak = 1
while j<=n andalso prime(j)-prime(j-1) < prime(j-1)-prime(j-2) 'identical to above, but for the inequality sign
streak += 1
j+=1
wend
if streak > record then
champ = i-1
record = streak
end if
next i
 
print "The longest sequence of descending primes (with their difference from the last one) is:"
for i = champ+1 to champ+record
print prime(i-1);" (";prime(i)-prime(i-1);") ";
next i
print prime(i-1)</syntaxhighlight>
{{out}}
<pre>The longest sequence of ascending primes (with their difference from the last one) is:
128981 (2) 128983 (4) 128987 (6) 128993 (8) 129001 (10) 129011 (12) 129023 (14) 129037
 
The longest sequence of descending primes (with their difference from the last one) is:
322171 (22) 322193 (20) 322213 (16) 322229 (8) 322237 (6) 322243 (4) 322247 (2) 322249</pre>
 
=={{header|C}}==
{{trans|Wren}}
More or less.
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
 
bool *sieve(int limit) {
int i, p;
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) {
int 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;
}
}
return c;
}
 
void longestSeq(int *primes, int pc, bool asc) {
int i, j, d, pd = 0, lls = 1, lcs = 1;
int longSeqs[25][10] = {{2}};
int lsl[25] = {1};
int currSeq[10] = {2};
const char *dir = asc ? "ascending" : "descending";
for (i = 1; i < pc; ++i) {
d = primes[i] - primes[i-1];
if ((asc && d <= pd) || (!asc && d >= pd)) {
if (lcs > lsl[0]) {
memcpy((void *)longSeqs[0], (void *)currSeq, lcs * sizeof(int));
lsl[0] = lcs;
lls = 1;
} else if (lcs == lsl[0]) {
memcpy((void *)longSeqs[lls], (void *)currSeq, lcs * sizeof(int));
lsl[lls++] = lcs;
}
currSeq[0] = primes[i-1];
currSeq[1] = primes[i];
lcs = 2;
} else {
currSeq[lcs++] = primes[i];
}
pd = d;
}
if (lcs > lsl[0]) {
memcpy((void *)longSeqs[0], (void *)currSeq, lcs * sizeof(int));
lsl[0] = lcs;
lls = 1;
} else if (lcs == lsl[0]) {
memcpy((void *)longSeqs[lls], (void *)currSeq, lcs * sizeof(int));
lsl[lls++] = lcs;
}
printf("Longest run(s) of primes with %s differences is %d:\n", dir, lsl[0]);
for (i = 0; i < lls; ++i) {
int *ls = longSeqs[i];
for (j = 0; j < lsl[i]-1; ++j) printf("%d (%d) ", ls[j], ls[j+1] - ls[j]);
printf("%d\n", ls[lsl[i]-1]);
}
printf("\n");
}
 
int main() {
const int limit = 999999;
int i, j, pc = 0;
bool *c = sieve(limit);
for (i = 0; i < limit; ++i) {
if (!c[i]) ++pc;
}
int *primes = (int *)malloc(pc * sizeof(int));
for (i = 0, j = 0; i < limit; ++i) {
if (!c[i]) primes[j++] = i;
}
free(c);
printf("For primes < 1 million:\n");
longestSeq(primes, pc, true);
longestSeq(primes, pc, false);
free(primes);
return 0;
}</syntaxhighlight>
 
{{out}}
<pre>
For primes < 1 million:
Longest run(s) of primes with ascending differences is 8:
128981 (2) 128983 (4) 128987 (6) 128993 (8) 129001 (10) 129011 (12) 129023 (14) 129037
402581 (2) 402583 (4) 402587 (6) 402593 (8) 402601 (12) 402613 (18) 402631 (60) 402691
665111 (2) 665113 (4) 665117 (6) 665123 (8) 665131 (10) 665141 (12) 665153 (24) 665177
 
Longest run(s) of primes with descending differences is 8:
322171 (22) 322193 (20) 322213 (16) 322229 (8) 322237 (6) 322243 (4) 322247 (2) 322249
752207 (44) 752251 (12) 752263 (10) 752273 (8) 752281 (6) 752287 (4) 752291 (2) 752293
</pre>
 
=={{header|C sharp|C#}}==
Extended the limit up to see what would happen.
<langsyntaxhighlight lang="csharp">using System.Linq;
using System.Collections.Generic;
using TG = System.Tuple<int, int>;
Line 162 ⟶ 392:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>For primes up to 1,000,000:
Line 196 ⟶ 426:
=={{header|C++}}==
{{libheader|Primesieve}}
<langsyntaxhighlight lang="cpp">#include <cstdint>
#include <iostream>
#include <vector>
Line 248 ⟶ 478:
print_diffs(v);
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 263 ⟶ 493:
 
This task uses [http://www.rosettacode.org/wiki/Extensible_prime_generator#The_functions Extensible Prime Generator (F#)]
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
The code makes heavy use of "Sieve" object developed for other Rosetta Code tasks. The Sieve object is described here: [[Extensible_prime_generator#Delphi]]
 
<syntaxhighlight lang="Delphi">
 
 
procedure LongestAscendDescend(Memo: TMemo);
{Find the longest Ascending and Descending sequences of primes}
var I: integer;
var Sieve: TPrimeSieve;
 
procedure FindLongestSequence(Ascend: boolean);
{Find the longest sequence - Ascend controls}
{ whether it ascending or descending}
var I,J,Count,BestCount,BestStart: integer;
var S: string;
 
function Compare(N1,N2: integer; Ascend: boolean): boolean;
{Compare for ascending or descending}
begin
if Ascend then Result:=N1>N2
else Result:=N1<N2;
end;
 
begin
BestStart:=0; BestCount:=0;
{Check all the primes in the sieve}
for I:=2 to High(Sieve.Primes)-1 do
begin
J:=I + 1;
Count:= 1;
{Count all the elements in the sequence}
while (j<=High(Sieve.Primes)) and
Compare(Sieve.Primes[J]-Sieve.Primes[J-1],Sieve.Primes[J-1]-Sieve.Primes[j-2],Ascend) do
begin
Inc(Count);
Inc(J);
end;
{Save the info if it is the best so far}
if Count > BestCount then
begin
BestStart:=I-1;
BestCount:= Count;
end;
end;
Memo.Lines.Add('Count = '+IntToStr(BestCount+1));
{Display the sequence}
S:='[';
for I:=BestStart to BestStart+BestCount do
begin
S:=S+IntToStr(Sieve.Primes[I]);
if I<(BestStart+BestCount) then S:=S+' ('+IntToStr(Sieve.Primes[I+1]-Sieve.Primes[I])+') ';
end;
S:=S+']';
Memo.Lines.Add(S);
end;
 
 
 
begin
Sieve:=TPrimeSieve.Create;
try
{Generate all primes below 1 million}
Sieve.Intialize(1000000);
 
Memo.Lines.Add('The longest sequence of ascending primes');
FindLongestSequence(True);
Memo.Lines.Add('The longest sequence of ascending primes');
FindLongestSequence(False);
finally Sieve.Free; end;
end;
 
 
</syntaxhighlight>
{{out}}
<pre>
The longest sequence of ascending primes
Count = 8
[128981 (2) 128983 (4) 128987 (6) 128993 (8) 129001 (10) 129011 (12) 129023 (14) 129037]
The longest sequence of ascending primes
Count = 8
[322171 (22) 322193 (20) 322213 (16) 322229 (8) 322237 (6) 322243 (4) 322247 (2) 322249]
Elapsed Time: 18.386 ms.
 
</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight>
fastfunc nextprim num .
repeat
i = 2
while i <= sqrt num and num mod i <> 0
i += 1
.
until num mod i <> 0
num += 1
.
return num
.
proc getseq dir . maxprim maxcnt .
maxcnt = 0
pri = 2
repeat
prev = pri
pri = nextprim (pri + 1)
until pri > 1000000
d0 = d
d = (pri - prev) * dir
if d > d0
cnt += 1
else
if cnt > maxcnt
maxcnt = cnt
maxprim = prim0
.
prim0 = prev
cnt = 1
.
.
.
proc outseq pri max . .
write pri & " "
for i to max
pri = nextprim (pri + 1)
write pri & " "
.
print ""
.
getseq 1 pri max
outseq pri max
getseq -1 pri max
outseq pri max
</syntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// Longest ascending and decending sequences of difference between consecutive primes: Nigel Galloway. April 5th., 2021
let fN g fW=primes32()|>Seq.takeWhile((>)g)|>Seq.pairwise|>Seq.fold(fun(n,i,g)el->let w=fW el in match w>n with true->(w,el::i,g) |_->(w,[el],if List.length i>List.length g then i else g))(0,[],[])
for i in [1;2;6;12;18;100] do let _,_,g=fN(i*1000000)(fun(n,g)->g-n) in printfn "Longest ascending upto %d000000->%d:" i (g.Length+1); g|>List.rev|>List.iter(fun(n,g)->printf "%d (%d) %d " n (g-n) g); printfn ""
let _,_,g=fN(i*1000000)(fun(n,g)->n-g) in printfn "Longest decending upto %d000000->%d:" i (g.Length+1); g|>List.rev|>List.iter(fun(n,g)->printf "%d (%d) %d " n (g-n) g); printfn ""
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 298 ⟶ 665:
Real: 00:00:04.708
</pre>
 
=={{header|Factor}}==
{{works with|Factor|0.99 2021-02-05}}
<langsyntaxhighlight lang="factor">USING: arrays assocs formatting grouping io kernel literals math
math.primes math.statistics sequences sequences.extras
tools.memory.private ;
Line 327 ⟶ 695:
printf [ .run ] each ; inline
 
[ < ] [ > ] [ .runs nl ] bi@</langsyntaxhighlight>
{{out}}
<pre>
Line 340 ⟶ 708:
</pre>
 
=={{header|FreeBASICGo}}==
{{trans|Wren}}
Use any of the primality testing code on this site as an include; I won't reproduce it here.
<syntaxhighlight lang="go">package main
<lang freebasic>#define UPPER 1000000
#include"isprime.bas"
 
import (
dim as uinteger champ = 0, record = 0, streak, i, j, n
"fmt"
"rcu"
)
 
const LIMIT = 999999
'first generate all the primes below UPPER
redim as uinteger prime(1 to 2)
prime(1) = 2 : prime(2) = 3
for i = 5 to UPPER step 2
if isprime(i) then
redim preserve prime(1 to ubound(prime) + 1)
prime(ubound(prime)) = i
end if
next i
n = ubound(prime)
 
var primes = rcu.Primes(LIMIT)
'now look for the longest streak of ascending primes
for i = 2 to n-1
j = i + 1
streak = 1
while j<=n andalso prime(j)-prime(j-1) > prime(j-1)-prime(j-2)
streak += 1
j+=1
wend
if streak > record then
champ = i-1
record = streak
end if
next i
 
func longestSeq(dir string) {
print "The longest sequence of ascending primes (with their difference from the last one) is:"
pd := 0
for i = champ+1 to champ+record
longSeqs := [][]int{{2}}
print prime(i-1);" (";prime(i)-prime(i-1);") ";
currSeq := []int{2}
next i
for i := 1; i < len(primes); i++ {
print prime(i-1) : print
d := primes[i] - primes[i-1]
'now for the descending ones
if (dir == "ascending" && d <= pd) || (dir == "descending" && d >= pd) {
if len(currSeq) > len(longSeqs[0]) {
longSeqs = [][]int{currSeq}
} else if len(currSeq) == len(longSeqs[0]) {
longSeqs = append(longSeqs, currSeq)
}
currSeq = []int{primes[i-1], primes[i]}
} else {
currSeq = append(currSeq, primes[i])
}
pd = d
}
if len(currSeq) > len(longSeqs[0]) {
longSeqs = [][]int{currSeq}
} else if len(currSeq) == len(longSeqs[0]) {
longSeqs = append(longSeqs, currSeq)
}
fmt.Println("Longest run(s) of primes with", dir, "differences is", len(longSeqs[0]), ":")
for _, ls := range longSeqs {
var diffs []int
for i := 1; i < len(ls); i++ {
diffs = append(diffs, ls[i]-ls[i-1])
}
for i := 0; i < len(ls)-1; i++ {
fmt.Print(ls[i], " (", diffs[i], ") ")
}
fmt.Println(ls[len(ls)-1])
}
fmt.Println()
}
 
func main() {
record = 0 : champ = 0
fmt.Println("For primes < 1 million:\n")
for i = 2 to n-1
for _, dir := range []string{"ascending", "descending"} {
j = i + 1
longestSeq(dir)
streak = 1
}
while j<=n andalso prime(j)-prime(j-1) < prime(j-1)-prime(j-2) 'identical to above, but for the inequality sign
}</syntaxhighlight>
streak += 1
j+=1
wend
if streak > record then
champ = i-1
record = streak
end if
next i
 
print "The longest sequence of descending primes (with their difference from the last one) is:"
for i = champ+1 to champ+record
print prime(i-1);" (";prime(i)-prime(i-1);") ";
next i
print prime(i-1)</lang>
{{out}}
<pre>
<pre>The longest sequence of ascending primes (with their difference from the last one) is:
For primes < 1 million:
 
Longest run(s) of primes with ascending differences is 8 :
128981 (2) 128983 (4) 128987 (6) 128993 (8) 129001 (10) 129011 (12) 129023 (14) 129037
402581 (2) 402583 (4) 402587 (6) 402593 (8) 402601 (12) 402613 (18) 402631 (60) 402691
665111 (2) 665113 (4) 665117 (6) 665123 (8) 665131 (10) 665141 (12) 665153 (24) 665177
 
TheLongest longest sequencerun(s) of descending primes (with theirdescending differencedifferences fromis the8 last one) is:
322171 (22) 322193 (20) 322213 (16) 322229 (8) 322237 (6) 322243 (4) 322247 (2) 322249</pre>
752207 (44) 752251 (12) 752263 (10) 752273 (8) 752281 (6) 752287 (4) 752291 (2) 752293
</pre>
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">import Data.Numbers.Primes (primes)
 
-- generates consecutive subsequences defined by given equivalence relation
consecutives equiv = filter ((> 1) . length) . go []
where
go r [] = [r]
go [] (h : t) = go [h] t
go (y : ys) (h : t)
| y `equiv` h = go (h : y : ys) t
| otherwise = (y : ys) : go [h] t
 
-- finds maximal values in a list and returns the first one
maximumBy g (h : t) = foldr f h t
where
f r x = if g r < g x then x else r
 
-- the task implementation
task ord n = reverse $ p + s : p : (fst <$> rest)
where
(p, s) : rest =
maximumBy length $
consecutives (\(_, a) (_, b) -> a `ord` b) $
differences $
takeWhile (< n) primes
differences l = zip l $ zipWith (-) (tail l) l</syntaxhighlight>
 
<pre>λ> reverse <$> consecutives (<) [1,0,1,2,3,4,3,2,3,4,5,6,7,6,5,4,3,4,5]
[[0,1,2,3,4],[2,3,4,5,6,7],[3,4,5]]
 
λ> task (<) 1000000
[128981,128983,128987,128993,129001,129011,129023,129037]
 
λ> task (>) 1000000
[322171,322193,322213,322229,322237,322243,322247,322249]</pre>
 
=={{header|J}}==
<syntaxhighlight lang="j"> ;{.(\: #@>) tris <@~.@,;._1~ <:/ 2 -/\ |: tris=: 3 ]\ p: i. p:inv 1e6
128981 128983 128987 128993 129001 129011 129023 129037
;{.(\: #@>) tris <@~.@,;._1~ >:/ 2 -/\ |: tris=: 3 ]\ p: i. p:inv 1e6
322171 322193 322213 322229 322237 322243 322247 322249</syntaxhighlight>
 
 
=={{header|Java}}==
<syntaxhighlight lang="java">
 
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
 
public final class ConsecutivePrimes {
 
public static void main(String[] aArgs) {
final int limit = 1_000_000;
List<Integer> primes = listPrimeNumbers(limit);
List<Integer> asc = new ArrayList<Integer>();
List<Integer> desc = new ArrayList<Integer>();
List<List<Integer>> maxAsc = new ArrayList<List<Integer>>();
List<List<Integer>> maxDesc = new ArrayList<List<Integer>>();
int maxAscSize = 0;
int maxDescSize = 0;
for ( int prime : primes ) {
final int ascSize = asc.size();
if ( ascSize > 1 && prime - asc.get(ascSize - 1) <= asc.get(ascSize - 1) - asc.get(ascSize - 2) ) {
asc = new ArrayList<Integer>(asc.subList(ascSize - 1, asc.size()));
}
asc.add(prime);
if ( asc.size() >= maxAscSize ) {
if ( asc.size() > maxAscSize ) {
maxAscSize = asc.size();
maxAsc.clear();
}
maxAsc.add( new ArrayList<Integer>(asc) );
}
final int descSize = desc.size();
if ( descSize > 1 && prime - desc.get(descSize - 1) >= desc.get(descSize - 1) - desc.get(descSize - 2) ) {
desc = new ArrayList<Integer>(desc.subList(descSize - 1, desc.size()));
}
desc.add(prime);
if ( desc.size() >= maxDescSize ) {
if ( desc.size() > maxDescSize ) {
maxDescSize = desc.size();
maxDesc.clear();
}
maxDesc.add( new ArrayList<Integer>(desc) );
}
}
System.out.println("Longest run(s) of ascending prime gaps up to " + limit + ":");
for ( List<Integer> list : maxAsc ) {
displayResult(list);
}
System.out.println();
System.out.println("Longest run(s) of descending prime gaps up to " + limit + ":");
for( List<Integer> list : maxDesc ) {
displayResult(list);
}
}
private static List<Integer> listPrimeNumbers(int aLimit) {
BitSet sieve = new BitSet(aLimit + 1);
sieve.set(2, aLimit + 1);
for ( int i = 2; i <= Math.sqrt(aLimit); i = sieve.nextSetBit(i + 1) ) {
for ( int j = i * i; j <= aLimit; j = j + i ) {
sieve.clear(j);
}
}
List<Integer> result = new ArrayList<Integer>(sieve.cardinality());
for ( int i = 2; i >= 0; i = sieve.nextSetBit(i + 1) ) {
result.add(i);
}
return result;
}
private static void displayResult(List<Integer> aList) {
for ( int i = 0; i < aList.size(); i++ ) {
if ( i > 0 ) {
System.out.print(" (" + ( aList.get(i) - aList.get(i - 1) ) + ") ");
}
System.out.print(aList.get(i));
}
System.out.println();
}
 
}
</syntaxhighlight>
{{ out }}
<pre>
Longest run(s) of ascending prime gaps up to 1000000:
128981 (2) 128983 (4) 128987 (6) 128993 (8) 129001 (10) 129011 (12) 129023 (14) 129037
402581 (2) 402583 (4) 402587 (6) 402593 (8) 402601 (12) 402613 (18) 402631 (60) 402691
665111 (2) 665113 (4) 665117 (6) 665123 (8) 665131 (10) 665141 (12) 665153 (24) 665177
 
Longest run(s) of descending prime gaps up to 1000000:
322171 (22) 322193 (20) 322213 (16) 322229 (8) 322237 (6) 322243 (4) 322247 (2) 322249
752207 (44) 752251 (12) 752263 (10) 752273 (8) 752281 (6) 752287 (4) 752291 (2) 752293
</pre>
 
=={{header|jq}}==
'''Adapted from [[#Wren|Wren]]'''
 
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
This entry assumes the availability of `is_prime`, for which a suitable definition can be found at
[[Erd%C5%91s-primes#jq]].
 
'''Preliminaries'''
<syntaxhighlight lang="jq"># For streams of strings or of arrays or of numbers:
def add(s): reduce s as $x (null; .+$x);
 
# Primes less than . // infinite
def primes:
(. // infinite) as $n
| if $n < 3 then empty
else 2, (range(3; $n) | select(is_prime))
end;
</syntaxhighlight>
'''The Task'''
<syntaxhighlight lang="jq"># Input: null or limit+1
# Output: informative strings
def longestSequences:
[primes] as $primes
| def longestSeq(direction):
{ pd: 0,
longSeqs: [[2]],
currSeq: [2] }
| reduce range( 1; $primes|length) as $i (.;
($primes[$i] - $primes[$i-1]) as $d
| if (direction == "ascending" and $d <= .pd) or (direction == "descending" and $d >= .pd)
then if (.currSeq|length) > (.longSeqs[0]|length)
then .longSeqs = [.currSeq]
else if (.currSeq|length) == (.longSeqs[0]|length)
then .longSeqs += [.currSeq]
else .
end
end
| .currSeq = [$primes[$i-1], $primes[$i]]
else .currSeq += [$primes[$i]]
end
| .pd = $d
)
| if (.currSeq|length) > (.longSeqs[0]|length)
then .longSeqs = [.currSeq]
else if (.currSeq|length) == (.longSeqs[0]|length)
then .longSeqs = .longSeqs + [.currSeq]
else .
end
end
 
| "Longest run(s) of primes with \(direction) differences is \(.longSeqs[0]|length):",
(.longSeqs[] as $ls
| add( range(1; $ls|length) | [$ls[.] - $ls[.-1]]) as $diffs
| add( range(0; $ls|length-1) | "\($ls[.]) (\($diffs[.])) ") + "\($ls[-1])" );
 
longestSeq("ascending"), "", longestSeq("descending");
"For primes < 1 million:",
( 1E6 | longestSequences )</syntaxhighlight>
{{out}}
<pre>
For primes < 1 million:
Longest run(s) of primes with ascending differences is 8:
128981 (2) 128983 (4) 128987 (6) 128993 (8) 129001 (10) 129011 (12) 129023 (14) 129037
402581 (2) 402583 (4) 402587 (6) 402593 (8) 402601 (12) 402613 (18) 402631 (60) 402691
665111 (2) 665113 (4) 665117 (6) 665123 (8) 665131 (10) 665141 (12) 665153 (24) 665177
 
Longest run(s) of primes with descending differences is 8:
322171 (22) 322193 (20) 322213 (16) 322229 (8) 322237 (6) 322243 (4) 322247 (2) 322249
752207 (44) 752251 (12) 752263 (10) 752273 (8) 752281 (6) 752287 (4) 752291 (2) 752293
</pre>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Primes
 
function primediffseqs(maxnum = 1_000_000)
Line 435 ⟶ 1,028:
 
primediffseqs()
</langsyntaxhighlight>{{out}}
<pre>
Ascending: [128981, 128983, 128987, 128993, 129001, 129011, 129023, 129037] Diffs: [2, 4, 6, 8, 10, 12, 14]
Descending: [322171, 322193, 322213, 322229, 322237, 322243, 322247, 322249] Diffs: [22, 20, 16, 8, 6, 4, 2]
</pre>
 
=={{header|Lua}}==
This task uses <code>primegen</code> from: [[Extensible_prime_generator#Lua]]
<syntaxhighlight lang="lua">function findcps(primelist, fcmp)
local currlist = {primelist[1]}
local longlist, prevdiff = currlist, 0
for i = 2, #primelist do
local diff = primelist[i] - primelist[i-1]
if fcmp(diff, prevdiff) then
currlist[#currlist+1] = primelist[i]
if #currlist > #longlist then
longlist = currlist
end
else
currlist = {primelist[i-1], primelist[i]}
end
prevdiff = diff
end
return longlist
end
 
primegen:generate(nil, 1000000)
cplist = findcps(primegen.primelist, function(a,b) return a>b end)
print("ASC ("..#cplist.."): ["..table.concat(cplist, " ").."]")
cplist = findcps(primegen.primelist, function(a,b) return a<b end)
print("DESC ("..#cplist.."): ["..table.concat(cplist, " ").."]")</syntaxhighlight>
{{out}}
<pre>ASC (8): [128981 128983 128987 128993 129001 129011 129023 129037]
DESC (8): [322171 322193 322213 322229 322237 322243 322247 322249]</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">prime = Prime[Range[PrimePi[10^6]]];
s = Split[Differences[prime], Less];
max = Max[Length /@ s];
diffs = Select[s, Length/*EqualTo[max]];
seqs = SequencePosition[Flatten[s], #, 1][[1]] & /@ diffs;
Take[prime, # + {0, 1}] & /@ seqs
 
s = Split[Differences[prime], Greater];
max = Max[Length /@ s];
diffs = Select[s, Length/*EqualTo[max]];
seqs = SequencePosition[Flatten[s], #, 1][[1]] & /@ diffs;
Take[prime, # + {0, 1}] & /@ seqs</syntaxhighlight>
{{out}}
<pre>128981 128983 128987 128993 129001 129011 129023 129037
402581 402583 402587 402593 402601 402613 402631 402691
665111 665113 665117 665123 665131 665141 665153 665177
 
322171 322193 322213 322229 322237 322243 322247 322249
752207 752251 752263 752273 752281 752287 752291 752293</pre>
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import math, strformat, sugar
 
const N = 1_000_000
Line 503 ⟶ 1,146:
echo()
echo "First longest sequence of consecutive primes with descending differences:"
echo longestSeq(Descending)</langsyntaxhighlight>
 
{{out}}
Line 513 ⟶ 1,156:
First longest sequence of consecutive primes with descending differences:
322171 (22) 322193 (20) 322213 (16) 322229 (8) 322237 (6) 322243 (4) 322247 (2) 322249</pre>
 
=={{header|Pari/GP}}==
Code is pretty reasonable, runs in ~70 ms at 1,000,000. Running under PARI (starting from gp2c translation) could take advantage of the diff structure of the prime table directly for small cases and avoid substantial overhead, gaining at least a factor of 2 in performance.
<syntaxhighlight lang="parigp">showPrecPrimes(p, n)=
{
my(v=vector(n));
v[n]=p;
forstep(i=n-1,1,-1,
v[i]=precprime(v[i+1]-1)
);
for(i=1,n, print1(v[i]" "));
}
list(lim)=
{
my(p=3,asc,dec,ar,dr,arAt=3,drAt=3,last=2);
forprime(q=5,lim,
my(g=q-p);
if(g<last,
asc=0;
if(desc++>dr,
dr=desc;
drAt=q
)
,g>last,
desc=0;
if(asc++>ar,
ar=asc;
arAt=q
)
,
asc=desc=0
);
p=q;
last=g
);
print("Descending differences:");
showPrecPrimes(drAt, dr+2);
print("\nAscending differences:");
showPrecPrimes(arAt, ar+2);
}
list(10^6)</syntaxhighlight>
{{out}}
<pre>Descending differences:
322171 322193 322213 322229 322237 322243 322247 322249
Ascending differences:
128981 128983 128987 128993 129001 129011 129023 129037</pre>
 
=={{header|Perl}}==
{{trans|Raku}}
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 546 ⟶ 1,235:
 
say "Longest run(s) of ascending prime gaps up to $limit:\n" . join "\n", runs('>');
say "\nLongest run(s) of descending prime gaps up to $limit:\n" . join "\n", runs('<');</langsyntaxhighlight>
{{out}}
<pre>Longest run(s) of ascending prime gaps up to 1000000:
Line 558 ⟶ 1,247:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #004080;">integer</span> <span style="color: #000000;">pn</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- prime numb</span>
<span style="color: #000000;">lp</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- last prime</span>
Line 585 ⟶ 1,274:
<span style="color: #0000FF;">{{</span><span style="color: #008000;">"ascending"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"descending"</span><span style="color: #0000FF;">}[</span><span style="color: #000000;">run</span><span style="color: #0000FF;">],</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">),</span><span style="color: #000000;">p</span><span style="color: #0000FF;">,</span><span style="color: #000000;">g</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
longest ascending run length 8: {128981,128983,128987,128993,129001,129011,129023,129037} gaps: {2,4,6,8,10,12,14}
longest descending run length 8: {322171,322193,322213,322229,322237,322243,322247,322249} gaps: {22,20,16,8,6,4,2}
</pre>
 
=={{header|Python}}==
<syntaxhighlight lang="python">
from sympy import sieve
 
primelist = list(sieve.primerange(2,1000000))
 
listlen = len(primelist)
 
# ascending
 
pindex = 1
old_diff = -1
curr_list=[primelist[0]]
longest_list=[]
 
while pindex < listlen:
 
diff = primelist[pindex] - primelist[pindex-1]
if diff > old_diff:
curr_list.append(primelist[pindex])
if len(curr_list) > len(longest_list):
longest_list = curr_list
else:
curr_list = [primelist[pindex-1],primelist[pindex]]
old_diff = diff
pindex += 1
print(longest_list)
 
# descending
 
pindex = 1
old_diff = -1
curr_list=[primelist[0]]
longest_list=[]
 
while pindex < listlen:
 
diff = primelist[pindex] - primelist[pindex-1]
if diff < old_diff:
curr_list.append(primelist[pindex])
if len(curr_list) > len(longest_list):
longest_list = curr_list
else:
curr_list = [primelist[pindex-1],primelist[pindex]]
old_diff = diff
pindex += 1
print(longest_list)
</syntaxhighlight>
 
{{out}}
<pre>
[128981, 128983, 128987, 128993, 129001, 129011, 129023, 129037]
[322171, 322193, 322213, 322229, 322237, 322243, 322247, 322249]
</pre>
 
=={{header|Raku}}==
 
<syntaxhighlight lang="raku" perl6line>use Math::Primesieve;
use Lingua::EN::Numbers;
 
Line 625 ⟶ 1,373:
say "Longest run(s) of ascending prime gaps up to {comma $limit}:\n" ~ runs(&infix:«>»);
 
say "\nLongest run(s) of descending prime gaps up to {comma $limit}:\n" ~ runs(&infix:«<»);</langsyntaxhighlight>
{{out}}
<pre>Longest run(s) of ascending prime gaps up to 1,000,000:
Line 637 ⟶ 1,385:
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program finds the longest sequence of consecutive primes where the differences */
/*──────────── between the primes are strictly ascending; also for strictly descending.*/
parse arg hi cols . /*obtain optional argument from the CL.*/
Line 667 ⟶ 1,415:
end /*j*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: !@.1=2; 0 @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; @.7=17; @.8=19 /*placeholdersdefine forlow primes (semaphores).*/
@.1=2; @.2=3; @.3=5; @.4=7; @.5=11 /*define some low primes. #=8; sq.#= @.# ** 2 /*number of primes so far; prime sqiare*/
!.2=1; !.3=1; !.5=1; !.7=1; !.11=1 /* " " " " flags. */
#=5; s.#= @.# **2 /*number of primes so far; prime². */
/* [↓] generate more primes ≤ high.*/
do j=@.#+2 by 2 to hi; parse var j '' -1 _ /*find odd primes from here on. */
parseif var j '' -1 _;==5 if then iterate; if _j// 3==50 then iterate /*J divisible÷ by 5? (right dig) J ÷ by 3? */
if j// 7==0 then iterate; if j// 311==0 then iterate /*" " 7? " " " " 311? */
if j//13==0 then iterate; if j// 717==0 then iterate /*" " 13? " " 7? " 17? */
do k=8 while sq.k<=j /* [] thedivide above 3by the linesknown savesodd timeprimes.*/
do k=5 while s.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; s sq.#= j*j; !.j= 1 /*bump # of Ps; assign next P; P²; P# square*/
end /*j*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: parse arg ?; if ? then AorD= 'ascending' /*choose which literal for display.*/
else AorD= 'descending' /* " " " " " */
@lrcptitle= ' longest run of consecutive primes whose differences between primes are' ,
'primes are 'strictly' AorD "and < " commas(hi)
say; say; say
if cols>0 then say ' index │'center(@lrcptitle, 1 + cols*(w+1) )
if cols>0 then say '───────┼'center("" , 1 + cols*(w+1), '─')
Cprimesfound= 0; idx= 1 /*initialize # of consecutive primes. */
$= /*a list of consecutive primes (so far)*/
do o=1 for words(seq.mxrun) /*show all consecutive primes in seq. */
c= commas( word(seq.mxrun, o) ) /*obtain the next prime in the sequence*/
Cprimesfound= Cprimesfound + 1 /*bump the number of consecutive primes*/
if cols=<=0 then iterate /*Buildbuild the list (to be shown later)? */
$= $ right(c, max(w, length(c) ) ) /*add a nice prime ──► list, allow big#*/
if Cprimesfound//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 /*o*/
if $\=='' then say center(idx, 7)"│" substr($, 2) /*maybe show residual output*/
if cols>0 then say '───────┴'center("" , 1 + cols*(w+1), '─')
say; say commas(Cprimes) ' was the'@lrcp; return</lang>
say; say commas(Cprimes) ' was the'title; return</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 708 ⟶ 1,454:
───────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────
1 │ 128,981 128,983 128,987 128,993 129,001 129,011 129,023 129,037
───────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────
 
8 was the longest run of consecutive primes whose differences between primes are strictly ascending and < 1,000,000
Line 716 ⟶ 1,463:
───────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────
1 │ 322,171 322,193 322,213 322,229 322,237 322,243 322,247 322,249
───────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────
 
8 was the longest run of consecutive primes whose differences between primes are strictly descending and < 1,000,000
</pre>
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">require "prime"
limit = 1_000_000
 
puts "First found longest run of ascending prime gaps up to #{limit}:"
p Prime.each(limit).each_cons(2).chunk_while{|(i1,i2), (j1,j2)| j1-i1 < j2-i2 }.max_by(&:size).flatten.uniq
puts "\nFirst found longest run of descending prime gaps up to #{limit}:"
p Prime.each(limit).each_cons(2).chunk_while{|(i1,i2), (j1,j2)| j1-i1 > j2-i2 }.max_by(&:size).flatten.uniq</syntaxhighlight>
{{out}}
<pre>First found longest run of ascending prime gaps up to 1000000:
[128981, 128983, 128987, 128993, 129001, 129011, 129023, 129037]
 
First found longest run of descending prime gaps up to 1000000:
[322171, 322193, 322213, 322229, 322237, 322243, 322247, 322249]
</pre>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">// [dependencies]
// primal = "0.3"
 
Line 779 ⟶ 1,543:
print_diffs(&v);
}
}</langsyntaxhighlight>
 
{{out}}
Line 791 ⟶ 1,555:
322171 (22) 322193 (20) 322213 (16) 322229 (8) 322237 (6) 322243 (4) 322247 (2) 322249
752207 (44) 752251 (12) 752263 (10) 752273 (8) 752281 (6) 752287 (4) 752291 (2) 752293
</pre>
 
=={{header|Sidef}}==
{{trans|Raku}}
<syntaxhighlight lang="ruby">func runs(f, arr) {
 
var run = 0
var diff = 0
var diffs = []
 
arr.each_cons(2, {|p1,p2|
var curr_diff = (p2 - p1)
f(curr_diff, diff) ? ++run : (run = 1)
diff = curr_diff
diffs << run
})
 
var max = diffs.max
var runs = []
 
diffs.indices_by { _ == max }.each {|i|
runs << arr.slice(i - max + 1, i + 1)
}
 
return runs
}
 
var limit = 1e6
var primes = limit.primes
 
say "Longest run(s) of ascending prime gaps up to #{limit.commify}:"
say runs({|a,b| a > b }, primes).join("\n")
 
say "\nLongest run(s) of descending prime gaps up to #{limit.commify}:"
say runs({|a,b| a < b }, primes).join("\n")</syntaxhighlight>
{{out}}
<pre>
Longest run(s) of ascending prime gaps up to 1,000,000:
[128981, 128983, 128987, 128993, 129001, 129011, 129023, 129037]
[402581, 402583, 402587, 402593, 402601, 402613, 402631, 402691]
[665111, 665113, 665117, 665123, 665131, 665141, 665153, 665177]
 
Longest run(s) of descending prime gaps up to 1,000,000:
[322171, 322193, 322213, 322229, 322237, 322243, 322247, 322249]
[752207, 752251, 752263, 752273, 752281, 752287, 752291, 752293]
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-math}}
<langsyntaxhighlight ecmascriptlang="wren">import "./math" for Int
 
var LIMIT = 999999
Line 830 ⟶ 1,639:
 
System.print("For primes < 1 million:\n")
for (dir in ["ascending", "descending"]) longestSeq.call(dir)</langsyntaxhighlight>
 
{{out}}
Line 845 ⟶ 1,654:
322171 (22) 322193 (20) 322213 (16) 322229 (8) 322237 (6) 322243 (4) 322247 (2) 322249
752207 (44) 752251 (12) 752263 (10) 752273 (8) 752281 (6) 752287 (4) 752291 (2) 752293
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">func IsPrime(N); \Return 'true' if N > 2 is a prime number
int N, I;
[if (N&1) = 0 \even number\ then return false;
for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
 
proc ShowSeq(Dir, Str); \Show longest sequence of distances between primes
int Dir, Str;
int Count, MaxCount, N, P, P0, D, D0, I, AP(1000), MaxAP(1000);
[Count:= 0; MaxCount:= 0;
P0:= 2; D0:= 0; \preceding prime and distance
AP(Count):= P0; Count:= Count+1;
for N:= 3 to 1_000_000-1 do
if IsPrime(N) then
[P:= N; \got a prime number
D:= P - P0; \distance from preceding prime
if D*Dir > D0*Dir then
[AP(Count):= P; Count:= Count+1;
if Count > MaxCount then \save best sequence
[MaxCount:= Count;
for I:= 0 to MaxCount-1 do
MaxAP(I):= AP(I);
];
]
else
[Count:= 0; \restart sequence
AP(Count):= P0; Count:= Count+1; \possible beginning
AP(Count):= P; Count:= Count+1;
];
P0:= P; D0:= D;
];
Text(0, "Longest sequence of "); Text(0, Str);
Text(0, " distances between primes: "); IntOut(0, MaxCount); CrLf(0);
for I:= 0 to MaxCount-2 do
[IntOut(0, MaxAP(I));
Text(0, " (");
IntOut(0, MaxAP(I+1) - MaxAP(I));
Text(0, ") ");
];
IntOut(0, MaxAP(I)); CrLf(0);
];
 
[ShowSeq(+1, "ascending"); \main
ShowSeq(-1, "descending");
]</syntaxhighlight>
 
{{out}}
<pre>
Longest sequence of ascending distances between primes: 8
128981 (2) 128983 (4) 128987 (6) 128993 (8) 129001 (10) 129011 (12) 129023 (14) 129037
Longest sequence of descending distances between primes: 8
322171 (22) 322193 (20) 322213 (16) 322229 (8) 322237 (6) 322243 (4) 322247 (2) 322249
</pre>
2,023

edits