How to resolve the algorithm Consecutive primes with ascending or descending differences step by step in the Perl 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 Perl 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 Perl programming language
Source code in the perl programming language
use strict;
use warnings;
use feature 'say';
use ntheory 'primes';
use List::AllUtils <indexes max>;
my $limit = 1000000;
my @primes = @{primes( $limit )};
sub runs {
my($op) = @_;
my @diff = my $diff = my $run = 1;
push @diff, map {
my $next = $primes[$_] - $primes[$_ - 1];
if ($op eq '>') { if ($next > $diff) { ++$run } else { $run = 1 } }
else { if ($next < $diff) { ++$run } else { $run = 1 } }
$diff = $next;
$run
} 1 .. $#primes;
my @prime_run;
my $max = max @diff;
for my $r ( indexes { $_ == $max } @diff ) {
push @prime_run, join ' ', map { $primes[$r - $_] } reverse 0..$max
}
@prime_run
}
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('<');
You may also check:How to resolve the algorithm Totient function step by step in the Lua programming language
You may also check:How to resolve the algorithm Jacobsthal numbers step by step in the Mathematica/Wolfram Language programming language
You may also check:How to resolve the algorithm Loops/While step by step in the ALGOL W programming language
You may also check:How to resolve the algorithm Greatest common divisor step by step in the Emacs Lisp programming language
You may also check:How to resolve the algorithm Anagrams step by step in the Tcl programming language