Consecutive primes with ascending or descending differences: Difference between revisions

Added Easylang
m (→‎{{header|Haskell}}: Specified import expression)
(Added Easylang)
 
(15 intermediate revisions by 10 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 477 ⟶ 780:
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">import Data.Numbers.Primes (primes)
Uses prime generator implemented in the [[Sieve_of_Eratosthenes#Improved_efficiency_Wheels]].
<lang haskell>import Data.Numbers.Primes (primes)
 
-- generates consecutive subsequences defined by given equivalence relation
Line 502 ⟶ 804:
differences $
takeWhile (< n) primes
differences l = zip l $ zipWith (-) (tail l) l</langsyntaxhighlight>
 
<pre>λ> reverse <$> consecutives (<) [1,0,1,2,3,4,3,2,3,4,5,6,7,6,5,4,3,4,5]
Line 512 ⟶ 814:
λ> 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 543 ⟶ 1,028:
 
primediffseqs()
</langsyntaxhighlight>{{out}}
<pre>
Ascending: [128981, 128983, 128987, 128993, 129001, 129011, 129023, 129037] Diffs: [2, 4, 6, 8, 10, 12, 14]
Line 551 ⟶ 1,036:
=={{header|Lua}}==
This task uses <code>primegen</code> from: [[Extensible_prime_generator#Lua]]
<langsyntaxhighlight lang="lua">function findcps(primelist, fcmp)
local currlist = {primelist[1]}
local longlist, prevdiff = currlist, 0
Line 573 ⟶ 1,058:
print("ASC ("..#cplist.."): ["..table.concat(cplist, " ").."]")
cplist = findcps(primegen.primelist, function(a,b) return a<b end)
print("DESC ("..#cplist.."): ["..table.concat(cplist, " ").."]")</langsyntaxhighlight>
{{out}}
<pre>ASC (8): [128981 128983 128987 128993 129001 129011 129023 129037]
Line 579 ⟶ 1,064:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">prime = Prime[Range[PrimePi[10^6]]];
s = Split[Differences[prime], Less];
max = Max[Length /@ s];
Line 590 ⟶ 1,075:
diffs = Select[s, Length/*EqualTo[max]];
seqs = SequencePosition[Flatten[s], #, 1][[1]] & /@ diffs;
Take[prime, # + {0, 1}] & /@ seqs</langsyntaxhighlight>
{{out}}
<pre>128981 128983 128987 128993 129001 129011 129023 129037
Line 600 ⟶ 1,085:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import math, strformat, sugar
 
const N = 1_000_000
Line 661 ⟶ 1,146:
echo()
echo "First longest sequence of consecutive primes with descending differences:"
echo longestSeq(Descending)</langsyntaxhighlight>
 
{{out}}
Line 674 ⟶ 1,159:
=={{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.
<langsyntaxhighlight lang="parigp">showPrecPrimes(p, n)=
{
my(v=vector(n));
Line 711 ⟶ 1,196:
showPrecPrimes(arAt, ar+2);
}
list(10^6)</langsyntaxhighlight>
{{out}}
<pre>Descending differences:
Line 721 ⟶ 1,206:
{{trans|Raku}}
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 750 ⟶ 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 762 ⟶ 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 789 ⟶ 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>
Line 797 ⟶ 1,282:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">
from sympy import sieve
 
Line 847 ⟶ 1,332:
print(longest_list)
</syntaxhighlight>
</lang>
 
{{out}}
Line 857 ⟶ 1,342:
=={{header|Raku}}==
 
<syntaxhighlight lang="raku" perl6line>use Math::Primesieve;
use Lingua::EN::Numbers;
 
Line 888 ⟶ 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 900 ⟶ 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 963 ⟶ 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 984 ⟶ 1,469:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require "prime"
limit = 1_000_000
 
Line 990 ⟶ 1,475:
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</langsyntaxhighlight>
{{out}}
<pre>First found longest run of ascending prime gaps up to 1000000:
Line 1,000 ⟶ 1,485:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">// [dependencies]
// primal = "0.3"
 
Line 1,058 ⟶ 1,543:
print_diffs(&v);
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,074 ⟶ 1,559:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func runs(f, arr) {
 
var run = 0
Line 1,104 ⟶ 1,589:
 
say "\nLongest run(s) of descending prime gaps up to #{limit.commify}:"
say runs({|a,b| a < b }, primes).join("\n")</langsyntaxhighlight>
{{out}}
<pre>
Line 1,119 ⟶ 1,604:
=={{header|Wren}}==
{{libheader|Wren-math}}
<langsyntaxhighlight ecmascriptlang="wren">import "./math" for Int
 
var LIMIT = 999999
Line 1,154 ⟶ 1,639:
 
System.print("For primes < 1 million:\n")
for (dir in ["ascending", "descending"]) longestSeq.call(dir)</langsyntaxhighlight>
 
{{out}}
Line 1,172 ⟶ 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 1,220 ⟶ 1,705:
[ShowSeq(+1, "ascending"); \main
ShowSeq(-1, "descending");
]</langsyntaxhighlight>
 
{{out}}
2,045

edits