How to resolve the algorithm Consecutive primes with ascending or descending differences step by step in the Raku programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Consecutive primes with ascending or descending differences step by step in the Raku programming language

Table of Contents

Problem Statement

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.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Consecutive primes with ascending or descending differences step by step in the Raku programming language

Source code in the raku programming language

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


  

You may also check:How to resolve the algorithm XML/XPath step by step in the Factor programming language
You may also check:How to resolve the algorithm Short-circuit evaluation step by step in the Action! programming language
You may also check:How to resolve the algorithm Loops/Break step by step in the Oberon-2 programming language
You may also check:How to resolve the algorithm Circular primes step by step in the Go programming language
You may also check:How to resolve the algorithm Doubly-linked list/Traversal step by step in the Axe programming language