Consecutive primes with ascending or descending differences: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added Rust solution)
(Added C++ solution)
Line 166: Line 166:
Descending, found run of 10 consecutive primes:
Descending, found run of 10 consecutive primes:
11938793 (60) 11938853 (38) 11938891 (28) 11938919 (14) 11938933 (10) 11938943 (8) 11938951 (6) 11938957 (4) 11938961 (2) 11938963</pre>
11938793 (60) 11938853 (38) 11938891 (28) 11938919 (14) 11938933 (10) 11938943 (8) 11938951 (6) 11938957 (4) 11938961 (2) 11938963</pre>

=={{header|C++}}==
{{libheader|Primesieve}}
<lang cpp>#include <cstdint>
#include <iostream>
#include <vector>
#include <primesieve.hpp>

void print_diffs(const std::vector<uint64_t>& vec) {
for (size_t i = 0, n = vec.size(); i != n; ++i) {
if (i != 0)
std::cout << " (" << vec[i] - vec[i - 1] << ") ";
std::cout << vec[i];
}
std::cout << '\n';
}

int main() {
std::cout.imbue(std::locale(""));
std::vector<uint64_t> asc, desc;
std::vector<std::vector<uint64_t>> max_asc, max_desc;
size_t max_asc_len = 0, max_desc_len = 0;
uint64_t prime;
const uint64_t limit = 1000000;
for (primesieve::iterator pi; (prime = pi.next_prime()) < limit; ) {
size_t alen = asc.size();
if (alen > 1 && prime - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2])
asc.erase(asc.begin(), asc.end() - 1);
asc.push_back(prime);
if (asc.size() >= max_asc_len) {
if (asc.size() > max_asc_len) {
max_asc_len = asc.size();
max_asc.clear();
}
max_asc.push_back(asc);
}
size_t dlen = desc.size();
if (dlen > 1 && prime - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2])
desc.erase(desc.begin(), desc.end() - 1);
desc.push_back(prime);
if (desc.size() >= max_desc_len) {
if (desc.size() > max_desc_len) {
max_desc_len = desc.size();
max_desc.clear();
}
max_desc.push_back(desc);
}
}
std::cout << "Longest run(s) of ascending prime gaps up to " << limit << ":\n";
for (const auto& v : max_asc)
print_diffs(v);
std::cout << "\nLongest run(s) of descending prime gaps up to " << limit << ":\n";
for (const auto& v : max_desc)
print_diffs(v);
return 0;
}</lang>

{{out}}
<pre>
Longest run(s) of ascending prime gaps up to 1,000,000:
128,981 (2) 128,983 (4) 128,987 (6) 128,993 (8) 129,001 (10) 129,011 (12) 129,023 (14) 129,037
402,581 (2) 402,583 (4) 402,587 (6) 402,593 (8) 402,601 (12) 402,613 (18) 402,631 (60) 402,691
665,111 (2) 665,113 (4) 665,117 (6) 665,123 (8) 665,131 (10) 665,141 (12) 665,153 (24) 665,177

Longest run(s) of descending prime gaps up to 1,000,000:
322,171 (22) 322,193 (20) 322,213 (16) 322,229 (8) 322,237 (6) 322,243 (4) 322,247 (2) 322,249
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|Factor}}==
=={{header|Factor}}==

Revision as of 13:59, 3 April 2021

Consecutive primes with ascending or descending differences is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
Task



Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending.

Do the same for sequences of primes where the differences are strictly descending.

In both cases, show the sequence for primes   <   1 000 000.

If there are multiple sequences of the same length, only the first need be shown.



ALGOL 68

<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 #
   PROC prime list = ( INT n )[]INT:
        BEGIN
           # sieve the primes to n #
           INT no = 0, yes = 1;
           [ 1 : n ]INT p;
           p[ 1 ] := no; p[ 2 ] := yes;
           FOR i FROM 3 BY 2 TO n DO p[ i ] := yes OD;
           FOR i FROM 4 BY 2 TO n DO p[ i ] := no  OD;
           FOR i FROM 3 BY 2 TO ENTIER sqrt( n ) DO
               IF p[ i ] = yes THEN FOR s FROM i * i BY i + i TO n DO p[ s ] := no OD FI
           OD;
           # replace the sieve with a list #
           INT p pos := 0;
           FOR i TO n DO IF p[ i ] = yes THEN p[ p pos +:= 1 ] := i FI OD;
           p[ 1 : p pos ]
        END # prime list # ;
   # find the longest sequence of primes where the successive differences are ascending #
   INT max number   = 1 000 000;
   []INT primes     = prime list( max number );
   INT asc length  := 0;
   INT asc start   := 0;
   INT desc length := 0;
   INT desc start  := 0;
   FOR p FROM LWB primes TO UPB primes DO
       INT prev diff := 0;
       INT length    := 1;
       FOR s FROM p + 1 TO UPB primes
       WHILE INT diff = primes[ s ] - primes[ s - 1 ];
             diff > prev diff
       DO
           length   +:= 1;
           prev diff := diff
       OD;
       IF length > asc length THEN
           # found a longer sequence #
           asc length := length;
           asc start  := p
       FI
   OD;
   # find the longest sequence of primes where the successive differences are descending #
   FOR p FROM LWB primes TO UPB primes DO
       INT prev diff := max number + 1;
       INT length    := 1;
       FOR s FROM p + 1 TO UPB primes
       WHILE INT diff = primes[ s ] - primes[ s - 1 ];
             diff < prev diff
       DO
           length   +:= 1;
           prev diff := diff
       OD;
       IF length > desc length THEN
           # found a longer sequence #
           desc length := length;
           desc start  := p
       FI
   OD;
   # show the sequences #
   print( ( "For primes up to ", whole( max number, 0 ), newline ) );
   print( ( "    Longest sequence of primes with ascending differences contains "
          , whole( asc length, 0 )
          , " primes, first such sequence:"
          , newline
          , "(differences in brackets):"
          , newline
          , "        "
          )
        );
   print( ( whole( primes[ asc start ], 0 ) ) );
   FOR p FROM asc start + 1 TO asc start + ( asc length - 1 ) DO
       print( ( " (", whole( primes[ p ] - primes[ p - 1 ], 0 ), ") ", whole( primes[ p ], 0 ) ) )
   OD;
   print( ( newline ) );
   print( ( "    Longest sequence of primes with descending differences contains "
          , whole( asc length, 0 )
          , " primes, first such sequence:"
          , newline
          , "(differences in brackets):"
          , newline
          , "        "
          )
        );
   print( ( whole( primes[ desc start ], 0 ) ) );
   FOR p FROM desc start + 1 TO desc start + ( desc length - 1 ) DO
       print( ( " (", whole( primes[ p ] - primes[ p - 1 ], 0 ), ") ", whole( primes[ p ], 0 ) ) )
   OD;
   print( ( newline ) )

END</lang>

Output:
For primes up to 1000000
    Longest sequence of primes with ascending differences contains 8 primes, first such sequence:
(differences in brackets):
        128981 (2) 128983 (4) 128987 (6) 128993 (8) 129001 (10) 129011 (12) 129023 (14) 129037
    Longest sequence of primes with descending differences contains 8 primes, first such sequence:
(differences in brackets):
        322171 (22) 322193 (20) 322213 (16) 322229 (8) 322237 (6) 322243 (4) 322247 (2) 322249

C#

Extended the limit up to see what would happen. <lang csharp>using System.Linq; using System.Collections.Generic; using TG = System.Tuple<int, int>; using static System.Console;

class Program { static void Main(string[] args) {

       const int mil = (int)1e6; foreach (var amt in new int[] { 1, 2, 6, 12, 18 }) {
           int lmt = mil * amt, lg = 0, ng, d, ld = 0; var desc = new string[] { "A", "", "De" };
           int[] mx = new int[] { 0, 0, 0 }, bi = new int[] { 0, 0, 0 }, c = new int[] { 2, 2, 2 };
           WriteLine("For primes up to {0:n0}:", lmt); var pr = PG.Primes(lmt).ToArray();
           for (int i = 0; i < pr.Length; i++) { ng = pr[i].Item2; d = ng.CompareTo(lg) + 1; if (ld == d) c[2 - d]++;
               else { if (c[d] > mx[d]) { mx[d] = c[d]; bi[d] = i - mx[d] - 1; } c[d] = 2; } ld = d; lg = ng; }
           for (int r = 0; r <= 2; r += 2) { Write("{0}scending, found run of {1} consecutive primes:\n  {2} ",
               desc[r], mx[r] + 1, pr[bi[r]++].Item1); foreach (var itm in pr.Skip(bi[r]).Take(mx[r]))
                   Write("({0}) {1} ", itm.Item2, itm.Item1); WriteLine(r == 0 ? "" : "\n"); } } } }

class PG { public static IEnumerable<TG> Primes(int lim) {

       bool[] flags = new bool[lim + 1]; int j = 3, lj = 2;
       for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)
           if (!flags[j]) { yield return new TG(j, j - lj); lj = j;
               for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }
       for (; j <= lim; j += 2) if (!flags[j]) { yield return new TG(j, j - lj); lj = j; } } }</lang>
Output:
For primes up to 1,000,000:
Ascending, found run of 8 consecutive primes:
  128981 (2) 128983 (4) 128987 (6) 128993 (8) 129001 (10) 129011 (12) 129023 (14) 129037
Descending, found run of 8 consecutive primes:
  322171 (22) 322193 (20) 322213 (16) 322229 (8) 322237 (6) 322243 (4) 322247 (2) 322249

For primes up to 2,000,000:
Ascending, found run of 9 consecutive primes:
  1319407 (4) 1319411 (8) 1319419 (10) 1319429 (14) 1319443 (16) 1319459 (18) 1319477 (32) 1319509 (34) 1319543
Descending, found run of 8 consecutive primes:
  322171 (22) 322193 (20) 322213 (16) 322229 (8) 322237 (6) 322243 (4) 322247 (2) 322249

For primes up to 6,000,000:
Ascending, found run of 9 consecutive primes:
  1319407 (4) 1319411 (8) 1319419 (10) 1319429 (14) 1319443 (16) 1319459 (18) 1319477 (32) 1319509 (34) 1319543
Descending, found run of 9 consecutive primes:
  5051309 (32) 5051341 (28) 5051369 (14) 5051383 (10) 5051393 (8) 5051401 (6) 5051407 (4) 5051411 (2) 5051413

For primes up to 12,000,000:
Ascending, found run of 9 consecutive primes:
  1319407 (4) 1319411 (8) 1319419 (10) 1319429 (14) 1319443 (16) 1319459 (18) 1319477 (32) 1319509 (34) 1319543
Descending, found run of 10 consecutive primes:
  11938793 (60) 11938853 (38) 11938891 (28) 11938919 (14) 11938933 (10) 11938943 (8) 11938951 (6) 11938957 (4) 11938961 (2) 11938963

For primes up to 18,000,000:
Ascending, found run of 10 consecutive primes:
  17797517 (2) 17797519 (4) 17797523 (8) 17797531 (10) 17797541 (12) 17797553 (20) 17797573 (28) 17797601 (42) 17797643 (50) 17797693
Descending, found run of 10 consecutive primes:
  11938793 (60) 11938853 (38) 11938891 (28) 11938919 (14) 11938933 (10) 11938943 (8) 11938951 (6) 11938957 (4) 11938961 (2) 11938963

C++

Library: Primesieve

<lang cpp>#include <cstdint>

  1. include <iostream>
  2. include <vector>
  3. include <primesieve.hpp>

void print_diffs(const std::vector<uint64_t>& vec) {

   for (size_t i = 0, n = vec.size(); i != n; ++i) {
       if (i != 0)
           std::cout << " (" << vec[i] - vec[i - 1] << ") ";
       std::cout << vec[i];
   }
   std::cout << '\n';

}

int main() {

   std::cout.imbue(std::locale(""));
   std::vector<uint64_t> asc, desc;
   std::vector<std::vector<uint64_t>> max_asc, max_desc;
   size_t max_asc_len = 0, max_desc_len = 0;
   uint64_t prime;
   const uint64_t limit = 1000000;
   for (primesieve::iterator pi; (prime = pi.next_prime()) < limit; ) {
       size_t alen = asc.size();
       if (alen > 1 && prime - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2])
           asc.erase(asc.begin(), asc.end() - 1);
       asc.push_back(prime);
       if (asc.size() >= max_asc_len) {
           if (asc.size() > max_asc_len) {
               max_asc_len = asc.size();
               max_asc.clear();
           }
           max_asc.push_back(asc);
       }
       size_t dlen = desc.size();
       if (dlen > 1 && prime - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2])
           desc.erase(desc.begin(), desc.end() - 1);
       desc.push_back(prime);
       if (desc.size() >= max_desc_len) {
           if (desc.size() > max_desc_len) {
               max_desc_len = desc.size();
               max_desc.clear();
           }
           max_desc.push_back(desc);
       }
   }
   std::cout << "Longest run(s) of ascending prime gaps up to " << limit << ":\n";
   for (const auto& v : max_asc)
       print_diffs(v);
   std::cout << "\nLongest run(s) of descending prime gaps up to " << limit << ":\n";
   for (const auto& v : max_desc)
       print_diffs(v);
   return 0;

}</lang>

Output:
Longest run(s) of ascending prime gaps up to 1,000,000:
128,981 (2) 128,983 (4) 128,987 (6) 128,993 (8) 129,001 (10) 129,011 (12) 129,023 (14) 129,037
402,581 (2) 402,583 (4) 402,587 (6) 402,593 (8) 402,601 (12) 402,613 (18) 402,631 (60) 402,691
665,111 (2) 665,113 (4) 665,117 (6) 665,123 (8) 665,131 (10) 665,141 (12) 665,153 (24) 665,177

Longest run(s) of descending prime gaps up to 1,000,000:
322,171 (22) 322,193 (20) 322,213 (16) 322,229 (8) 322,237 (6) 322,243 (4) 322,247 (2) 322,249
752,207 (44) 752,251 (12) 752,263 (10) 752,273 (8) 752,281 (6) 752,287 (4) 752,291 (2) 752,293

Factor

Works with: Factor version 0.99 2021-02-05

<lang factor>USING: arrays assocs formatting grouping io kernel literals math math.primes math.statistics sequences sequences.extras tools.memory.private ;

<< CONSTANT: limit 1,000,000 >>

CONSTANT: primes $[ limit primes-upto ]

run ( n quot -- seq quot )
   [ primes ] [ <clumps> ] [ ] tri*
   '[ differences _ monotonic? ] ; inline
max-run ( quot -- n )
   1 swap '[ 1 + dup _ run find drop ] loop 1 - ; inline
runs ( quot -- seq )
   [ max-run ] keep run filter ; inline
.run ( seq -- )
   dup differences [ [ commas ] map ] bi@
   [ "(" ")" surround ] map 2array round-robin " " join print ;
.runs ( quot -- )
   [ runs ] keep [ < ] = "rising" "falling" ? limit commas
   "Largest run(s) of %s gaps between primes less than %s:\n"
   printf [ .run ] each ; inline

[ < ] [ > ] [ .runs nl ] bi@</lang>

Output:
Largest run(s) of rising gaps between primes less than 1,000,000:
128,981 (2) 128,983 (4) 128,987 (6) 128,993 (8) 129,001 (10) 129,011 (12) 129,023 (14) 129,037
402,581 (2) 402,583 (4) 402,587 (6) 402,593 (8) 402,601 (12) 402,613 (18) 402,631 (60) 402,691
665,111 (2) 665,113 (4) 665,117 (6) 665,123 (8) 665,131 (10) 665,141 (12) 665,153 (24) 665,177

Largest run(s) of falling gaps between primes less than 1,000,000:
322,171 (22) 322,193 (20) 322,213 (16) 322,229 (8) 322,237 (6) 322,243 (4) 322,247 (2) 322,249
752,207 (44) 752,251 (12) 752,263 (10) 752,273 (8) 752,281 (6) 752,287 (4) 752,291 (2) 752,293

Julia

<lang julia>using Primes

function primediffseqs(maxnum = 1_000_000)

   mprimes = primes(maxnum)
   diffs = map(p -> mprimes[p[1] + 1] - p[2], enumerate(@view mprimes[begin:end-1]))
   incstart, decstart, bestinclength, bestdeclength = 1, 1, 0, 0
   for i in 1:length(diffs)-1
       foundinc, founddec = false, false
       for j in i+1:length(diffs)
           if !foundinc && diffs[j] <= diffs[j - 1]
               if (runlength = j - i) > bestinclength
                   bestinclength, incstart = runlength, i
               end
               foundinc = true
           end
           if !founddec && diffs[j] >= diffs[j - 1]
               if (runlength = j - i) > bestdeclength
                   bestdeclength, decstart = runlength, i
               end
               founddec = true
           end
           foundinc && founddec && break
       end
   end
   println("Ascending: ", mprimes[incstart:incstart+bestinclength], " Diffs: ", diffs[incstart:incstart+bestinclength-1])
   println("Descending: ", mprimes[decstart:decstart+bestdeclength], " Diffs: ", diffs[decstart:decstart+bestdeclength-1])

end

primediffseqs()

</lang>

Output:
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]

Phix

integer pn = 1, -- prime numb
        lp = 2, -- last prime
        lg = 0, -- last gap
        pd = 0  -- prev d
sequence cr = {0,0},    -- curr run [a,d]
         mr = {{0},{0}} -- max runs  ""
while true do
    pn += 1
    integer p = get_prime(pn), gap = p-lp,
            d = compare(gap,lg)
    if p>1e6 then exit end if
    if d then
        integer i = (3-d)/2
        cr[i] = iff(d=pd?cr[i]:lp!=2)+1
        if cr[i]>mr[i][1] then mr[i] = {cr[i],pn} end if
    end if
    {pd,lp,lg} = {d,p,gap}
end while

for run=1 to 2 do
    integer {l,e} = mr[run]
    sequence p = apply(tagset(e,e-l),get_prime),
             g = sq_sub(p[2..$],p[1..$-1])
    printf(1,"longest %s run length %d: %v gaps: %v\n",
       {{"ascending","descending"}[run],length(p),p,g})
end for
Output:
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}

Raku

<lang perl6>use Math::Primesieve; use Lingua::EN::Numbers;

my $sieve = Math::Primesieve.new;

my $limit = 1000000;

my @primes = $sieve.primes($limit);

sub runs (&op) {

   my $diff = 1;
   my $run = 1;
   my @diff = flat 1, (1..^@primes).map: {
       my $next = @primes[$_] - @primes[$_ - 1];
       if &op($next, $diff) { ++$run } else { $run = 1 }
       $diff = $next;
       $run;
   }
   my $max = max @diff;
   my @runs = @diff.grep: * == $max, :k;
   @runs.map( {
       my @run = (0..$max).reverse.map: -> $r { @primes[$_ - $r] }
       flat roundrobin(@run».&comma, @run.rotor(2 => -1).map({[R-] $_})».fmt('(%d)'));
   } ).join: "\n"

}

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:«<»);</lang>

Output:
Longest run(s) of ascending prime gaps up to 1,000,000:
128,981 (2) 128,983 (4) 128,987 (6) 128,993 (8) 129,001 (10) 129,011 (12) 129,023 (14) 129,037
402,581 (2) 402,583 (4) 402,587 (6) 402,593 (8) 402,601 (12) 402,613 (18) 402,631 (60) 402,691
665,111 (2) 665,113 (4) 665,117 (6) 665,123 (8) 665,131 (10) 665,141 (12) 665,153 (24) 665,177

Longest run(s) of descending prime gaps up to 1,000,000:
322,171 (22) 322,193 (20) 322,213 (16) 322,229 (8) 322,237 (6) 322,243 (4) 322,247 (2) 322,249
752,207 (44) 752,251 (12) 752,263 (10) 752,273 (8) 752,281 (6) 752,287 (4) 752,291 (2) 752,293

REXX

<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.*/ if hi== | hi=="," then hi= 1000000 /* " " " " " " */ if cols== | cols=="," then cols= 10 /* " " " " " " */ call genP /*build array of semaphores for primes.*/ w= 10 /*width of a number in any column. */ call fRun 1; call show 1 /*find runs with ascending prime diffs.*/ call fRun 0; call show 0 /* " " " descending " " */ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? /*──────────────────────────────────────────────────────────────────────────────────────*/ fRun: parse arg ?; mxrun=0; seq.= /*max run length; lists of prime runs.*/

                                                /*search for consecutive primes  <  HI.*/
       do j=2  for #-2;   cp= @.j;   jn= j+1    /*CP: current prime;  JN:  next j      */
       diff= @.jn - cp                          /*get difference between last 2 primes.*/
       cnt= 1;                       run=       /*initialize the   CNT   and   RUN.    */
              do k= jn+1  to #-2;    km= k-1    /*look for more primes in this run.    */
              if ?  then if @.k-@.km<=diff  then leave  /*Diff. too small? Stop looking*/
                                            else nop
                    else if @.k-@.km>=diff  then leave  /*  "    "  large?   "     "   */
              run= run  @.k;         cnt= cnt+1 /*append a prime to the run; bump count*/
              diff= @.k - @.km                  /*calculate difference for next prime. */
              end   /*k*/
       if cnt<=mxrun  then iterate              /*This run too short? Then keep looking*/
       mxrun= max(mxrun, cnt)                   /*define a new maximum run (seq) length*/
       seq.mxrun= cp  @.jn  run                 /*full populate the sequence (RUN).    */
       end   /*j*/;                   return

/*──────────────────────────────────────────────────────────────────────────────────────*/ genP: !.= 0 /*placeholders for primes (semaphores).*/

     @.1=2;  @.2=3;  @.3=5;  @.4=7;  @.5=11     /*define some low primes.              */
     !.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                  /*find odd primes from here on.        */
       parse var j  -1 _; if     _==5  then iterate  /*J divisible by 5?  (right dig)*/
                            if j// 3==0  then iterate  /*"     "      " 3?             */
                            if j// 7==0  then iterate  /*"     "      " 7?             */
                                                /* [↑]  the above  3  lines saves time.*/
              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.#= j*j;   !.j= 1  /*bump # of Ps; assign next P;  P²; P# */
       end          /*j*/;           return

/*──────────────────────────────────────────────────────────────────────────────────────*/ show: parse arg ?; if ? then AorD= 'ascending'

                         else AorD= 'descending'
                  @lrcp= ' longest run of consecutive primes whose differences between' ,
                         'primes are strictly'      AorD      "and  < "      commas(hi)
      say;   say;    say
      if cols>0 then say ' index │'center(@lrcp,     1 + cols*(w+1)     )
      if cols>0 then say '───────┼'center(""   ,     1 + cols*(w+1), '─')
      Cprimes= 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*/
         Cprimes= Cprimes + 1                   /*bump the number of consecutive primes*/
         if cols==0            then iterate     /*Build the list  (to be shown later)? */
         $= $ right(c, max(w, length(c) ) )     /*add a nice prime ──► list, allow big#*/
         if Cprimes//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*/
      say;            say commas(Cprimes)  ' was the'@lrcp;        return</lang>
output   when using the default inputs:
 index │  longest run of consecutive primes whose differences between primes are strictly ascending and  <  1,000,000
───────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────
   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



 index │  longest run of consecutive primes whose differences between primes are strictly descending and  <  1,000,000
───────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────
   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

Rust

<lang rust>// [dependencies] // primal = "0.3"

fn print_diffs(vec: Vec<usize>) {

   for i in 0..vec.len() {
       if i > 0 {
           print!(" ({}) ", vec[i] - vec[i - 1]);
       }
       print!("{}", vec[i]);
   }
   println!();

}

fn main() {

   let limit = 1000000;
   let mut asc = Vec::new();
   let mut desc = Vec::new();
   let mut max_asc = Vec::new();
   let mut max_desc = Vec::new();
   let mut max_asc_len = 0;
   let mut max_desc_len = 0;
   for p in primal::Sieve::new(limit)
       .primes_from(2)
       .take_while(|x| *x < limit)
   {
       let alen = asc.len();
       if alen > 1 && p - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2] {
           asc = asc.split_off(alen - 1);
       }
       asc.push(p);
       if asc.len() >= max_asc_len {
           if asc.len() > max_asc_len {
               max_asc_len = asc.len();
               max_asc.clear();
           }
           max_asc.push(asc.clone());
       }
       let dlen = desc.len();
       if dlen > 1 && p - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2] {
           desc = desc.split_off(dlen - 1);
       }
       desc.push(p);
       if desc.len() >= max_desc_len {
           if desc.len() > max_desc_len {
               max_desc_len = desc.len();
               max_desc.clear();
           }
           max_desc.push(desc.clone());
       }
   }
   println!("Longest run(s) of ascending prime gaps up to {}:", limit);
   for v in max_asc {
       print_diffs(v);
   }
   println!("\nLongest run(s) of descending prime gaps up to {}:", limit);
   for v in max_desc {
       print_diffs(v);
   }

}</lang>

Output:
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