# Largest difference between adjacent primes

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Largest difference between adjacent primes 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.

## 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 primes = primes_upto(1'000'000)

V maxdiff = 0
L(n) 1 .< primes.len
maxdiff = max(maxdiff, primes[n] - primes[n - 1])

print(‘Largest difference is ’maxdiff)```
Output:
```Largest difference is 114
```

## ALGOL 68

Note, to run this with Algol 68G, the command line option `--heap 256M` should be specified to allow a larger heap size.
As with the Wren, Phix, etc. samples, shows the gaps at a few other places.

```BEGIN # find the largest gap between adjacent primes up to 10 000 000 #
[]BOOL prime = PRIMESIEVE 10 000 000; # sieve the primes to 10 000 000 #
# find the largest gap between primes #
INT max gap     :=  0; # gap between 2 and 3 #
INT max prime   :=  0; # the prime with the maximum gap #
INT max prev    :=  0; # the prime before the maximum gap #
INT prev prime  :=  2; # the previous prime #
INT power of 10 := 10; # next number to print the gap for #
FOR i FROM 3 BY 2 TO UPB prime DO
IF prime[ i ] THEN
# have a prime #
INT gap = i - prev prime;
IF gap > max gap THEN
# have a bigger gap than before #
max prime := i;
max prev  := prev prime;
max gap   := gap
FI;
prev prime    := i
FI;
IF i = power of 10 - 1 THEN
# have reached the next power of 10 - report the max gap so far #
print( ( "Largest gap between primes up to ", whole( power of 10, -9 )
, ": ", whole( max gap, -9 ), " between "
, whole( max prev, 0 ), " and ", whole( max prime, 0 )
, newline
)
);
power of 10 *:= 10
FI
OD
END```
Output:
```Largest gap between primes up to        10:         2 between 3 and 5
Largest gap between primes up to       100:         8 between 89 and 97
Largest gap between primes up to      1000:        20 between 887 and 907
Largest gap between primes up to     10000:        36 between 9551 and 9587
Largest gap between primes up to    100000:        72 between 31397 and 31469
Largest gap between primes up to   1000000:       114 between 492113 and 492227
Largest gap between primes up to  10000000:       154 between 4652353 and 4652507
```

## Arturo

```primes: select range.step:2 3 1e6 => prime?

pair: couple primes drop primes
| maximum'p -> p\1 - p\0
| <=

print "Largest prime gap under a million is:"
print ~"|pair\1 - pair\0| between |pair\0| and |pair\1|"
```
Output:
```Largest prime gap under a million is:
114 between 492113 and 492227```

## AWK

```# syntax: GAWK -f LARGEST_DIFFERENCE_BETWEEN_ADJACENT_PRIMES.AWK
# converted from FreeBASIC
BEGIN {
stop = 1000000
champi = 3
champj = 5
i = 5
record = 2
while (i < stop) {
j = next_prime(i)
if (j-i > record) {
champi = i
champj = j
record = j - i
}
i = j
}
printf("The largest difference between adjacent primes < %d is %d between %d and %d\n",stop,record,champi,champj)
exit(0)
}
function next_prime(n,  q) { # finds the next prime after n
if (n == 0) { return(2) }
if (n < 3) { return(++n) }
q = n + 2
while (!is_prime(q)) {
q += 2
}
return(q)
}
function is_prime(n,  d) {
d = 5
if (n < 2) { return(0) }
if (n % 2 == 0) { return(n == 2) }
if (n % 3 == 0) { return(n == 3) }
while (d*d <= n) {
if (n % d == 0) { return(0) }
d += 2
if (n % d == 0) { return(0) }
d += 4
}
return(1)
}
```
Output:
```The largest difference between adjacent primes < 1000000 is 114 between 492113 and 492227
```

## C

Translation of: FreeBASIC
```#include<stdio.h>
#include<stdlib.h>

int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}

int nextprime( int p ) {
int i=0;
if(p==0) return 2;
if(p<3) return p+1;
while(!isprime(++i + p));
return i+p;
}

int main(void) {
int i=3, j=5, champ=3, champj=5, record=2;
for(i=3;j<=1000000;i=j) {
j=nextprime(i);
if(j-i>record) {
champ=i;
champj=j;
record = j-i;
}
}
printf( "The largest difference was %d, between %d and %d.\n", record, champ, champj );
return 0;
}
```
Output:
`The largest difference was 114, between 492113 and 492227.`

## C++

Library: Primesieve
```#include <iostream>
#include <locale>

#include <primesieve.hpp>

int main() {
std::cout.imbue(std::locale(""));
const uint64_t limit = 10000000000;
uint64_t max_diff = 0;
primesieve::iterator pi;
uint64_t p1 = pi.next_prime();
for (uint64_t p = 10;;) {
uint64_t p2 = pi.next_prime();
if (p2 >= p) {
std::cout << "Largest gap between primes under " << p << " is "
<< max_diff << ".\n";
if (p == limit)
break;
p *= 10;
}
if (p2 - p1 > max_diff)
max_diff = p2 - p1;
p1 = p2;
}
}
```
Output:
```Largest gap between primes under 10 is 2.
Largest gap between primes under 100 is 8.
Largest gap between primes under 1,000 is 20.
Largest gap between primes under 10,000 is 36.
Largest gap between primes under 100,000 is 72.
Largest gap between primes under 1,000,000 is 114.
Largest gap between primes under 10,000,000 is 154.
Largest gap between primes under 100,000,000 is 220.
Largest gap between primes under 1,000,000,000 is 282.
Largest gap between primes under 10,000,000,000 is 354.
```

## Delphi

Works with: Delphi version 6.0

```function IsPrime(N: integer): boolean;
{Optimised prime test - about 40% faster than the naive approach}
var I,Stop: integer;
begin
if (N = 2) or (N=3) then Result:=true
else if (n <= 1) or ((n mod 2) = 0) or ((n mod 3) = 0) then Result:= false
else
begin
I:=5;
Stop:=Trunc(sqrt(N));
Result:=False;
while I<=Stop do
begin
if ((N mod I) = 0) or ((N mod (i + 2)) = 0) then exit;
Inc(I,6);
end;
Result:=True;
end;
end;

procedure LargestPrimeDifference(Memo: TMemo);
{Find the largest difference between primes under 1 million}
var I: integer;
var P1,P2: integer;
var Delta,Largest,Prime1,Prime2: integer;
begin
Largest:=0;
P1:=1;
for I:=1 to 1000000-1 do
if IsPrime(I) then
begin
Delta:=I - P1;
if Delta>Largest then
begin
Largest:=Delta;
Prime1:=P1;
Prime2:=I;
end;
P1:=I;
end;
Memo.Lines.Add(Format('Prime1: %d  Prime2: %d    Diff:  %d',[Prime1,Prime2,Largest]));
end;
```
Output:
```Prime1: 492113  Prime2: 492227    Diff:  114

```

## EasyLang

```fastfunc isprim num .
i = 2
while i <= sqrt num
if num mod i = 0
return 0
.
i += 1
.
return 1
.
fastfunc nextprim prim .
repeat
prim += 1
until isprim prim = 1
.
return prim
.
prim = 2
repeat
prev = prim
prim = nextprim prim
until prim > 1e6
max = higher max (prim - prev)
.
print max```
Output:
```114
```

## F#

This task uses Extensible Prime Generator (F#)

```// Largest difference between adjacent primes. Nigel Galloway: November 22nd., 2021
let n,g=primes32()|>Seq.takeWhile((>)1000000)|>Seq.pairwise|>Seq.maxBy(fun(n,g)->g-n) in printfn \$"%d{g}-%d{n}=%d{g-n}"
```
Output:
```492227-492113=114
```

## Factor

See Largest difference between adjacent primes/Factor for a detailed explanation because why not?

Works with: Factor version 0.99 2021-06-02
```USING: arrays formatting kernel lists lists.lazy math math.order
math.primes.lists sequences ;

lprimes dup cdr lzip [ first2 2dup swap - -rot 3array ] lmap-lazy
[ second 1e6 < ] lwhile { 0 } [ max ] foldl

"Largest difference in adjacent primes under a million: %d between %d and %d.\n" vprintf
```
Output:
```Largest difference in adjacent primes under a million: 114 between 492113 and 492227.
```

## FreeBASIC

```#include "isprime.bas"

function nextprime( n as uinteger ) as uinteger
'finds the next prime after n
if n = 0 then return 2
if n < 3 then return n + 1
dim as integer q = n + 2
while not isprime(q)
q+=2
wend
return q
end function

dim as uinteger i = 5, j, champ=3, champj=5, record=2
while i<1000000
j = nextprime(i)
if j-i > record then
champ  = i
champj = j
record = j - i
end if
i = j
wend

print using "The largest difference was ####, between ####### and #######";record;champ;champj```
Output:
`The largest difference was   114 between  492113 and  492227`

## Go

Translation of: Wren
Library: go-rcu
```package main

import (
"fmt"
"rcu"
)

func main() {
limit := int(1e10 - 1)
primes := rcu.Primes(limit)
maxI := 0
maxDiff := 0
nextStop := 10
fmt.Println("The largest differences between adjacent primes under the following limits is:")
for i := 1; i < len(primes); i++ {
diff := primes[i] - primes[i-1]
if diff > maxDiff {
maxDiff = diff
maxI = i
}
if i == len(primes)-1 || primes[i+1] > nextStop {
c1 := rcu.Commatize(nextStop)
c2 := rcu.Commatize(primes[maxI])
c3 := rcu.Commatize(primes[maxI-1])
c4 := rcu.Commatize(maxDiff)
fmt.Printf("Under %s: %s - %s = %s\n", c1, c2, c3, c4)
nextStop *= 10
}
}
}
```
Output:
```The largest differences between adjacent primes under the following limits is:
Under 10: 5 - 3 = 2
Under 100: 97 - 89 = 8
Under 1,000: 907 - 887 = 20
Under 10,000: 9,587 - 9,551 = 36
Under 100,000: 31,469 - 31,397 = 72
Under 1,000,000: 492,227 - 492,113 = 114
Under 10,000,000: 4,652,507 - 4,652,353 = 154
Under 100,000,000: 47,326,913 - 47,326,693 = 220
Under 1,000,000,000: 436,273,291 - 436,273,009 = 282
Under 10,000,000,000: 4,302,407,713 - 4,302,407,359 = 354
```

## GW-BASIC

```10 R=2 : P=3 : P2=0
20 GOSUB 190
30 IF P2>1000000! THEN GOTO 70
40 IF P2-P > R THEN GOSUB 270
50 P=P2
60 GOTO 20
70 PRINT "The biggest difference was ";R;", between ";C1;" and ";C2
80 END
90 REM tests if a number is prime
100 Q=0
110 IF P = 2 THEN Q = 1:RETURN
120 IF P=3 THEN Q=1:RETURN
130 I=1
140 I=I+1
150 IF INT(P/I)*I = P THEN RETURN
160 IF I*I<=P THEN GOTO 140
170 Q = 1
180 RETURN
190 REM finds the next prime after P, result in P2
200 IF P = 0 THEN P2 = 2: RETURN
210 IF P<3 THEN P2 = P + 1: RETURN
220 T = P
230 P = P + 1
240 GOSUB 90
250 IF Q = 1 THEN P2 = P: P = T: RETURN
260 GOTO 230
270 C1=P
280 C2 = P2
290 R = P2 - P
300 RETURN```

```import Data.List.Split ( divvy )

isPrime :: Int -> Bool
isPrime n
|n == 2 = True
|n == 1 = False
|otherwise = null \$ filter (\i -> mod n i == 0 ) [2 .. root]
where
root :: Int
root = floor \$ sqrt \$ fromIntegral n

solution :: Int
solution = maximum \$ map (\li -> last li - head li ) \$ divvy 2 1 \$ filter
isPrime [1..999999]

main :: IO ( )
main = do
print solution
```
Output:
```114
```

## J

```   >./ 2 -~/\ p: i. _1 p: 1e6
114
```

## jq

Works with: jq

Works with gojq, the Go implementation of jq

See Erdős-primes#jq for a suitable definition of `is_prime` as used here.

```# Primes less than . // infinite
def primes:
(. // infinite) as \$n
| if \$n < 3 then empty
else 2, (range(3; \$n) | select(is_prime))
end;

reduce primes as \$p ( null;  # [prev, diff]
if . == null then [\$p, 0]
else (\$p - .[0]) as \$diff
| if \$diff > .[1] then [\$p, \$diff]
else .[0] = \$p
end
end)
| .[1];

pow(10; 1, 2, 6) | largest_difference_between_adjacent_primes```
Output:
```2
8
14
```

## Julia

```using Primes

function maxprimeinterval(nmax)
pri = primes(nmax)
diffs = [pri[i] - pri[i - 1] for i in 2:length(pri)]
diff, idx = findmax(diffs)
println("The maximum prime interval in primes up to \$nmax is \$diff: for example at [\$(pri[idx]), \$(pri[idx + 1])].")
end

foreach(n -> maxprimeinterval(10^n), 1:10)
```
Output:
```The maximum prime interval in primes up to 10 is 2: for example at [3, 5].
The maximum prime interval in primes up to 100 is 8: for example at [89, 97].
The maximum prime interval in primes up to 1000 is 20: for example at [887, 907].
The maximum prime interval in primes up to 10000 is 36: for example at [9551, 9587].
The maximum prime interval in primes up to 100000 is 72: for example at [31397, 31469].
The maximum prime interval in primes up to 1000000 is 114: for example at [492113, 492227].
The maximum prime interval in primes up to 10000000 is 154: for example at [4652353, 4652507].
The maximum prime interval in primes up to 100000000 is 220: for example at [47326693, 47326913].
The maximum prime interval in primes up to 1000000000 is 282: for example at [436273009, 436273291].
The maximum prime interval in primes up to 10000000000 is 354: for example at [4302407359, 4302407713].
```

## Mathematica / Wolfram Language

```Max[-Subtract @@@
Partition[Most@NestWhileList[NextPrime, 2, # < 1000000 &], 2, 1]]
```
Output:
```
114

```

## Nim

```import std/[bitops, math]

type Sieve = object
data: seq[byte]

func `[]`(sieve: Sieve; idx: Positive): bool =
## Return value of element at index "idx".
let idx = idx shr 1
let iByte = idx shr 3
let iBit = idx and 7
result = sieve.data[iByte].testBit(iBit)

func `[]=`(sieve: var Sieve; idx: Positive; val: bool) =
## Set value of element at index "idx".
let idx = idx shr 1
let iByte = idx shr 3
let iBit = idx and 7
if val: sieve.data[iByte].setBit(iBit)
else: sieve.data[iByte].clearBit(iBit)

func newSieve(lim: Positive): Sieve =
## Create a sieve with given maximal index.
result.data = newSeq[byte]((lim + 16) shr 4)

func initPrimes(lim: Positive): seq[Natural] =
## Initialize the list of primes from 2 to "lim".
var composite = newSieve(lim)
composite[1] = true
for n in countup(3, sqrt(lim.toFloat).int, 2):
if not composite[n]:
for k in countup(n * n, lim, 2 * n):
composite[k] = true
for n in countup(3, lim, 2):
if not composite[n]:

let primes = initPrimes(1_000_000)

var prev = 0
var largestDiff = 0
for n in primes:
largestDiff = max(largestDiff, n - prev)
prev = n
echo "Largest difference: ", largestDiff
```
Output:
```Largest difference: 114
```

## Pascal

### Free Pascal

```program primesieve;
// sieving small ranges of 65536 only odd numbers
//{\$O+,R+}
{\$IFDEF FPC}
{\$MODE DELPHI}{\$OPTIMIZATION ON,ALL}{\$CODEALIGN proc=16}
uses
sysutils;
{\$ENDIF}
{\$IFDEF WINDOWS}
{\$APPTYPE CONSOLE}
{\$ENDIF}

const
smlPrimes :array [0..10] of Byte = (2,3,5,7,11,13,17,19,23,29,31);
maxPreSievePrime = 17;
sieveSize = 1 shl 15;//32768*2 ->max count of FoundPrimes = 6542
type
tSievePrim = record
svdeltaPrime:word;//diff between actual and new prime
svSivOfs:word;
svSivNum:LongWord;// 1 shl (16+32) = 2.8e14
end;
var
{\$Align 16}
//primes up to 1E6-> sieving to 1E12
sievePrimes : array[0..78497] of tSievePrim;
{\$Align 16}
preSieve :array[0..3*5*7*11*13*17-1] of Byte;
{\$Align 16}
Sieve :array[0..sieveSize-1] of Byte;
{\$Align 16}
FoundPrimes : array[0..6542] of Word;
{\$Align 16}
Limit,OffSet,Dekalimit,MaxGap : Uint64;

SieveMaxIdx,
preSieveOffset,
SieveNum,
FoundPrimesCnt,
PrimPos,
LastInsertedSievePrime :NativeUInt;

procedure CopyPreSieveInSieve;forward;
procedure CollectPrimes;forward;
procedure sieveOneSieve;forward;

procedure preSieveInit;
var
i,pr,j,umf : NativeInt;
Begin
i := 1;// starts with pr = 3
umf := 1;
repeat
IF preSieve[i] =0 then
Begin
pr := 2*i+1;
j := i;
repeat
preSieve[j] := 1;
inc(j,pr);
until j> High(preSieve);
umf := umf*pr;
end;
inc(i);
until umf>High(preSieve);
preSieveOffset := 0;
end;

procedure CalcSievePrimOfs(lmt:NativeUint);
//lmt High(sievePrimes)
var
i,pr : NativeUInt;
sq : Uint64;
begin
pr := 0;
i := 0;
repeat
with sievePrimes[i] do
Begin
pr := pr+svdeltaPrime;
IF sqr(pr)  < (SieveSize*2) then
Begin
svSivNum := 0;
svSivOfs := (pr*pr-1) DIV 2;
end
else
Begin
SieveMaxIdx := i;
pr := pr-svdeltaPrime;
BREAK;
end;
end;
inc(i);
until i > lmt;

for i := i to lmt do
begin
with sievePrimes[i] do
Begin
pr := pr+svdeltaPrime;
sq := sqr(pr);
svSivNum := sq DIV (2*SieveSize);
svSivOfs := ( (sq - Uint64(svSivNum)*(2*SieveSize))-1)DIV 2;
end;
end;
end;

procedure InitSieve;
begin
preSieveOffset := 0;
SieveNum :=0;
CalcSievePrimOfs(PrimPos-1);
end;

procedure InsertSievePrimes;
var
j    :NativeUINt;
i,pr : NativeUInt;
begin
i := 0;
//ignore first primes already sieved with
if SieveNum = 0 then
repeat
inc(i);
until FoundPrimes[i] > maxPreSievePrime;

pr :=0;
j := Uint64(SieveNum)*SieveSize*2-LastInsertedSievePrime;
with sievePrimes[PrimPos] do
Begin
pr := FoundPrimes[i];
svdeltaPrime := pr+j;
j := pr;
end;
inc(PrimPos);
for i := i+1 to FoundPrimesCnt-1 do
Begin
IF PrimPos > High(sievePrimes) then
BREAK;
with sievePrimes[PrimPos] do
Begin
pr := FoundPrimes[i];
svdeltaPrime := (pr-j);
j := pr;
end;
inc(PrimPos);
end;
LastInsertedSievePrime :=Uint64(SieveNum)*SieveSize*2+pr;
end;

procedure sievePrimesInit;
var
i,j,pr:NativeInt;
Begin
LastInsertedSievePrime := 0;

PrimPos := 0;
preSieveOffset := 0;
SieveNum :=0;
CopyPreSieveInSieve;
repeat
while Sieve[i] = 1 do
inc(i);
pr := 2*i+1;
inc(i);
j := ((pr*pr)-1) DIV 2;
if j > High(Sieve) then
BREAK;
repeat
Sieve[j] := 1;
inc(j,pr);
until j > High(Sieve);
until false;

CollectPrimes;
InsertSievePrimes;
IF PrimPos < High(sievePrimes) then
Begin
InitSieve;
//Erste Sieb nochmals, aber ohne Eintrag
CopyPreSieveInSieve;
sieveOneSieve;
repeat
inc(SieveNum);
CopyPreSieveInSieve;
sieveOneSieve;
CollectPrimes;
InsertSievePrimes;
until PrimPos > High(sievePrimes);
end;
end;

procedure CopyPreSieveInSieve;
var
lmt : NativeInt;
Begin
lmt := preSieveOffset+sieveSize;
lmt := lmt-(High(preSieve)+1);
IF lmt<= 0 then
begin
Move(preSieve[preSieveOffset],Sieve[0],sieveSize);
if lmt <> 0 then
inc(preSieveOffset,sieveSize)
else
preSieveOffset := 0;
end
else
begin
Move(preSieve[preSieveOffset],Sieve[0],sieveSize-lmt);
Move(preSieve[0],Sieve[sieveSize-lmt],lmt);
preSieveOffset := lmt
end;
end;

procedure CollectPrimes;
var
pSieve : pbyte;
pFound : pWord;
i,idx : NativeInt;
Begin
pFound := @FoundPrimes[0];
idx := 0;
i := 0;
IF SieveNum = 0 then
Begin
repeat
pFound[idx] := smlPrimes[idx];
inc(idx);
until smlPrimes[idx]>maxPreSievePrime;
i := (smlPrimes[idx] -1) DIV 2;
end;

pSieve := @Sieve[0];
repeat
pFound[idx]:= 2*i+1;
inc(idx,1-pSieve[i]);
inc(i);
until i>High(Sieve);
FoundPrimesCnt:= idx;
end;

procedure sieveOneSieve;
var
i,j,pr,dSievNum :NativeUint;
Begin
pr := 0;
For i := 0 to SieveMaxIdx do
with sievePrimes[i] do
begin
pr := pr+svdeltaPrime;
IF svSivNum = sieveNum then
Begin
j := svSivOfs;
repeat
Sieve[j] := 1;
inc(j,pr);
until j > High(Sieve);
dSievNum := j DIV SieveSize;
svSivOfs := j-dSievNum*SieveSize;
inc(svSivNum,dSievNum);
end;
end;

i := SieveMaxIdx+1;
repeat
if i > High(SievePrimes) then
BREAK;
with sievePrimes[i] do
begin
if svSivNum > sieveNum then
Begin
SieveMaxIdx := I-1;
Break;
end;
pr := pr+svdeltaPrime;
j := svSivOfs;
repeat
Sieve[j] := 1;
inc(j,pr);
until j > High(Sieve);
dSievNum := j DIV SieveSize;
svSivOfs := j-dSievNum*SieveSize;
inc(svSivNum,dSievNum);
inc(i);
end;
until false;
end;

var
T1,T0,CNT,ActPrime,LastPrime,GapPrime : Int64;
i: Int32;

begin
T0 := GetTickCount64;
Limit := 10*1000*1000*1000;//99999999999;//
preSieveInit;
sievePrimesInit;

InitSieve;
offset := 0;
Cnt := 1;//==2
LastPrime := 2;
Dekalimit := 10;
MaxGap := 0;
writeln('Limit        Gap  First prime');
repeat
CopyPreSieveInSieve;sieveOneSieve;CollectPrimes;
inc(Cnt,FoundPrimesCnt);
inc(SieveNum);
//check for max gap
i := 0;
repeat
ActPrime := Offset+FoundPrimes[i];
If ActPrime > Dekalimit then
Begin
writeln(Dekalimit :12,MaxGap:4,GapPrime:12);
DekaLimit := 10 *DekaLimit;
end;
if ActPrime - LastPrime > MaxGap then
begin
MaxGap := ActPrime - LastPrime;
GapPrime:=  LastPrime;
end;
LastPrime := ActPrime;
inc(i);
until (i >= FoundPrimesCnt);

inc(offset,2*SieveSize);
until SieveNum > (Limit DIV (2*SieveSize));

T1 := GetTickCount64;
OffSet := Uint64(SieveNum-1)*(2*SieveSize);
// correct count to Limit
i := FoundPrimesCnt;
repeat
dec(i);
dec(cnt);
until (i = 0) OR (OffSet+FoundPrimes[i]<Limit);
writeln;
writeln(cnt,' in ',Limit,' takes ',T1-T0,' ms');
{\$IFDEF WINDOWS}
{\$ENDIF}
end.
```
@TIO.RUN:
```Limit        Gap  First prime
10   2           3
100   8          89
1000  20         887
10000  36        9551
100000  72       31397
1000000 114      492113
10000000 154     4652353
100000000 220    47326693
1000000000 282   436273009
10000000000 354  4302407359

455052511 in 10000000000 takes 14319 ms
```

## Perl

```use strict;
use warnings;
use Primesieve qw(generate_primes);

for my \$n (2..8) {
my @primes = generate_primes (1, 10**\$n);
my(\$max,\$p,\$diff) = 0;
map { (\$diff = \$primes[\$_] - \$primes[\$_-1]) > \$max and (\$max,\$p) = (\$diff,\$_-1) } 1..\$#primes;
printf "Largest prime gap up to %d: %d - between %d and %d.\n", 10**\$n, \$max, @primes[\$p,\$p+1];
}
```
Output:
```Largest prime gap up to 100: 8 - between 89 and 97.
Largest prime gap up to 1000: 20 - between 887 and 907.
Largest prime gap up to 10000: 36 - between 9551 and 9587.
Largest prime gap up to 100000: 72 - between 31397 and 31469.
Largest prime gap up to 1000000: 114 - between 492113 and 492227.
Largest prime gap up to 10000000: 154 - between 4652353 and 4652507.
Largest prime gap up to 100000000: 220 - between 47326693 and 47326913.```

## Phix

Translation of: Wren
```with javascript_semantics
atom t0 = time()
constant limit = iff(platform()=JS?1e8:1e9) - 1
sequence primes = get_primes_le(limit)
integer maxI = 0,
maxDiff = 0
atom nextStop = 10
printf(1,"The largest differences between adjacent primes under the following limits is:\n")
for i=2 to length(primes) do
integer diff = primes[i] - primes[i-1]
if diff>maxDiff then
maxDiff = diff
maxI = i
end if
if i==length(primes) or primes[i+1]>nextStop then
printf(1,"Under %,d: %,d - %,d = %,d\n", {nextStop, primes[maxI], primes[maxI-1], maxDiff})
nextStop *= 10
end if
end for
?elapsed(time()-t0)
```
Output:
```The largest differences between adjacent primes under the following limits is:
Under 10: 5 - 3 = 2
Under 100: 97 - 89 = 8
Under 1,000: 907 - 887 = 20
Under 10,000: 9,587 - 9,551 = 36
Under 100,000: 31,469 - 31,397 = 72
Under 1,000,000: 492,227 - 492,113 = 114
Under 10,000,000: 4,652,507 - 4,652,353 = 154
Under 100,000,000: 47,326,913 - 47,326,693 = 220
Under 1,000,000,000: 436,273,291 - 436,273,009 = 282
"12.7s"
```

Almost all the time is spent constructing the list of primes. It is about 4 times slower under pwa/p2js so limited to 1e8 when running in a browser to keep the time below 5s instead of over 50s.

## Python

```print("working...")
limit = 1000000
res1 = 0
res2 = 0
maxOld = 0
newDiff = 0
oldDiff = 0

def isPrime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True

for n in range(limit):
newDiff = n - maxOld
if isprime(n):
if (newDiff > oldDiff):
res1 = n
res2 = maxOld
oldDiff = newDiff
maxOld = n

diff = res1 - res2
print(res1)
print(res2)
print("Largest difference is = ",end="")
print(diff)
print("done...")
```
Output:
```492227
492113
Largest difference is = 114
```

## Raku

### Built-ins

```for 2..8 -> \$n {
printf "Largest prime gap up to {10 ** \$n}: %d - between %d and %d.\n", .[0], |.[1]
given max (^10**\$n).grep(&is-prime).rotor(2=>-1).map({.[1]-.[0],\$_})
}
```
Output:
```Largest prime gap up to 100: 8 - between 89 and 97.
Largest prime gap up to 1000: 20 - between 887 and 907.
Largest prime gap up to 10000: 36 - between 9551 and 9587.
Largest prime gap up to 100000: 72 - between 31397 and 31469.
Largest prime gap up to 1000000: 114 - between 492113 and 492227.
Largest prime gap up to 10000000: 154 - between 4652353 and 4652507.
Largest prime gap up to 100000000: 220 - between 47326693 and 47326913.```

Or, significantly faster using a

### Module

```use Math::Primesieve;
my \$sieve = Math::Primesieve.new;

for 2..8 -> \$n {
printf "Largest prime gap up to {10 ** \$n}: %d - between %d and %d.\n", .[0], |.[1]
given max \$sieve.primes(10 ** \$n).rotor(2=>-1).map({.[1]-.[0],\$_})
}
```

Same output

## Ring

```load "stdlib.ring"
see "working..." + nl
limit = 1000000
Primes = []
maxOld = 0
newDiff = 0
oldDiff = 0

for n = 1 to limit
newDiff = n - maxOld
if isprime(n)
if newDiff > oldDiff
oldDiff = newDiff
ok
maxOld = n
ok
next

len = len(Primes)
diff = Primes[len][1] - Primes[len][2]
see Primes[len(Primes)]
see nl + "Largest difference is = " + diff + nl
see "done..." + nl```
Output:
```working...
492227
492113
Largest difference is = 114
done...
```

## RPL

Works with: HP version 49
```≪ 1000000 PREVPRIME
DUP PREVPRIME DUP2 - UNROT
DO NIP DUP PREVPRIME
DUP2 - 4 PICK
IF OVER < THEN 3 UNPICK ELSE DROP END
UNTIL DUP 2 == END
DROP2
```
Output:
```1: 114
```

## Ruby

```require 'prime'

n = 1000000
pr1, pr2 = Prime.each(n).each_cons(2).max_by{|p1,p2| p2-p1}
puts "Largest difference between adjacent primes under #{n} is #{pr2-pr1} (#{pr2}-#{pr1})."
```
Output:
```Largest difference between adjacent primes under 1000000 is 114 (492227-492113).
```

## Rust

```fn is_prime( num : u32 ) -> bool {
if num == 1 {
return false ;
}
else {
let root : f32 = (num as f32).sqrt( ) ;
let limit : u32 = root.floor( ) as u32 ;
(2..=limit).filter( | &d | num % d == 0 ).collect::<Vec<u32>>( ).len( ) == 0
}
}

fn main() {
let target_primes : Vec<u32> = (2..1000000).filter( | &d | is_prime( d ) ).
collect( ) ;
let mut diff : u32 = target_primes[ 1 ] - target_primes[ 0 ] ;
let len = target_primes.len( ) ;
for i in 1..len - 1 {
let current_diff = target_primes[i + 1] - target_primes[ i ] ;
if current_diff > diff {
diff = current_diff ;
}
}
println!("{}" , diff ) ;
}
```
Output:
```114
```

## Sidef

```func prime_gap_records(upto) {

var gaps = []
var p = 2

each_prime(p.next_prime, upto, {|q|
gaps[q-p] := p
p = q
})

gaps.grep { defined(_) }
}

var upto   = 1e8
var primes = prime_gap_records(upto)

for n in (2 .. upto.ilog10) {

var b = primes.last_by {|p| p < 10**n } \\ break

printf("Largest prime gap up to 10^%s is %3s between %s and %s\n",
n, b.next_prime - b, b, b.next_prime)
}
```
Output:
```Largest prime gap up to 10^2 is   8 between 89 and 97
Largest prime gap up to 10^3 is  20 between 887 and 907
Largest prime gap up to 10^4 is  36 between 9551 and 9587
Largest prime gap up to 10^5 is  72 between 31397 and 31469
Largest prime gap up to 10^6 is 114 between 492113 and 492227
Largest prime gap up to 10^7 is 154 between 4652353 and 4652507
Largest prime gap up to 10^8 is 220 between 47326693 and 47326913
```

## Wren

Library: Wren-math
Library: Wren-fmt
```import "./math" for Int
import "./fmt" for Fmt

var limit = 1e9 - 1
var primes = Int.primeSieve(limit)
var maxI = 0
var maxDiff = 0
var nextStop = 10
System.print("The largest differences between adjacent primes under the following limits is:")
for (i in 1...primes.count) {
var diff = primes[i] - primes[i-1]
if (diff > maxDiff) {
maxDiff = diff
maxI = i
}
if (i == primes.count - 1 || primes[i+1] > nextStop)  {
Fmt.print("Under \$,d: \$,d - \$,d = \$,d", nextStop, primes[maxI], primes[maxI-1], maxDiff)
nextStop = nextStop * 10
}
}
```
Output:
```The largest differences between adjacent primes under the following limits is:
Under 10: 5 - 3 = 2
Under 100: 97 - 89 = 8
Under 1,000: 907 - 887 = 20
Under 10,000: 9,587 - 9,551 = 36
Under 100,000: 31,469 - 31,397 = 72
Under 1,000,000: 492,227 - 492,113 = 114
Under 10,000,000: 4,652,507 - 4,652,353 = 154
Under 100,000,000: 47,326,913 - 47,326,693 = 220
Under 1,000,000,000: 436,273,291 - 436,273,009 = 282
```

## XPL0

```def  Size = 1_000_000_000/2;            \sieve for odd numbers
int  Prime, I, K;
char Flags;
int  Limit, TenToThe, Max, Gap, I0, Prime0, Prime1;
[Flags:= MAlloc(Size+1);                \(heap only provides 64 MB)
for I:= 0 to Size do                    \set flags all true
Flags(I):= true;
for I:= 0 to Size do
if Flags(I) then                    \found a prime
[Prime:= I+I+3;
K:= I+Prime;                    \first multiple to strike off
while K <= Size do              \strike off all multiples
[Flags(K):= false;
K:= K+Prime;
];
];
Text(0, "Largest difference between adjacent primes under:
");
Limit:= 10;
for TenToThe:= 1 to 9 do
[Max:= 0;  I0:= 0;
for I:= 0 to Limit/2-3 do
[if Flags(I) then               \odd prime
[Gap:= I - I0;
if Gap > Max then
[Max:= Gap;
Prime0:= I0*2 + 3;
Prime1:= I *2 + 3;
];
I0:= I;
];
];
IntOut(0, Limit);  Text(0, " is ");
IntOut(0, Prime1); Text(0, " - ");
IntOut(0, Prime0); Text(0, " = ");
IntOut(0, Max*2);  CrLf(0);
Limit:= Limit*10;
];
]```
Output:
```Largest difference between adjacent primes under:
10 is 5 - 3 = 2
100 is 97 - 89 = 8
1000 is 907 - 887 = 20
10000 is 9587 - 9551 = 36
100000 is 31469 - 31397 = 72
1000000 is 492227 - 492113 = 114
10000000 is 4652507 - 4652353 = 154
100000000 is 47326913 - 47326693 = 220
1000000000 is 436273291 - 436273009 = 282
```