Consecutive primes with ascending or descending differences: Difference between revisions

Added Easylang
m (→‎{{header|REXX}}: added/changed whitespace and comments, optimized the GENP subroutine.)
(Added Easylang)
 
(28 intermediate revisions by 18 users not shown)
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 339 ⟶ 707:
752,207 (44) 752,251 (12) 752,263 (10) 752,273 (8) 752,281 (6) 752,287 (4) 752,291 (2) 752,293
</pre>
 
=={{header|FreeBASIC}}==
Use any of the primality testing code on this site as an include; I won't reproduce it here.
<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)</lang>
{{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|Go}}==
{{trans|Wren}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 460 ⟶ 763:
longestSeq(dir)
}
}</langsyntaxhighlight>
 
{{out}}
Line 472 ⟶ 775:
 
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|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
Line 477 ⟶ 999:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Primes
 
function primediffseqs(maxnum = 1_000_000)
Line 506 ⟶ 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 574 ⟶ 1,146:
echo()
echo "First longest sequence of consecutive primes with descending differences:"
echo longestSeq(Descending)</langsyntaxhighlight>
 
{{out}}
Line 584 ⟶ 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 617 ⟶ 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 629 ⟶ 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 656 ⟶ 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 696 ⟶ 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 708 ⟶ 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 771 ⟶ 1,448:
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'title; return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 789 ⟶ 1,466:
 
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 850 ⟶ 1,543:
print_diffs(&v);
}
}</langsyntaxhighlight>
 
{{out}}
Line 862 ⟶ 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 901 ⟶ 1,639:
 
System.print("For primes < 1 million:\n")
for (dir in ["ascending", "descending"]) longestSeq.call(dir)</langsyntaxhighlight>
 
{{out}}
Line 919 ⟶ 1,657:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="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;
Line 967 ⟶ 1,705:
[ShowSeq(+1, "ascending"); \main
ShowSeq(-1, "descending");
]</langsyntaxhighlight>
 
{{out}}
2,046

edits