Haskell, 132 130 bytes
f$[2..]>>= \x->[2..x]
f(x:y)n=do b<-randomIO;last$f y n:[pure(x,x+n)|b,p x,p$x+n]
p n=all((>0).mod n)[2..n-1]
import System.Random
Try it online!
The relevant function is f$[2..]>>= \x->[2..x]
, which takes n
as input and returns a random pair of primes (x,x+n)
.
Definitely not the shortest possible answer, but what I like about it is that, when given enough time, it will actually generate every possible pair of primes at distance \$n\$, no matter how large. Also, unlike my two other answers below, it has the nice advantage of actually taking less than a googol years to produce some output.
How?
The idea is to iterate over the list
[2..]>>= \x->[2..x]≡[2,2,3,2,3,4,2,3,4,5,2,3,4,5,6,2,3,4,5,6,7,...]
which contains every integer \$\ge 2\$ infinitely many times. Whenever we encounter a number \$x\$ such that \$x\$ and \$x+n\$ are prime, we output the pair \$(x,x+n)\$ with probability \$\frac{1}{2}\$ (b<-randomIO
picks a Bool
at random), otherwise we keep going. The program will halt with probability \$1\$, however the probability of outputting anything other than the first pair is very low, especially for larger values of \$n\$. The TIO link above runs the function \$1,\!000,\!000\$ times, and collect the unique results.
Haskell, 115 102 104 bytes
f n=do x<-randomIO;last$f n:[pure(x,x+n)|x>1,p x,p$x+n]
p n=all((>0).mod n)[2..n-1]
import System.Random
Try it online!
The relevant function here is f
.
This code will almost never run in a reasonable amount of time, but theoretically, if given enough time, it should output all the prime pairs \$(x,x+n)\$ with \$x<2^{63}\$ (the System.Random
random generator can't generate numbers larger than this).
How?
This is the naive approach: generate a random number \$x\$, check if \$x\$ and \$x+n\$ are prime, and in this case return \$(x,x+n)\$. Otherwise try again.
(2?)
x?n=do d<-randomIO;last$(x+d)?n:[pure(x,x+n)|d>0,x>1,p x,p$x+n]
p n=all((>0).mod n)[2..n-1]
import System.Random
Try it online!
The relevant function is (2?)
.
A mix of the two solutions above. It has the theoretical guarantees of the first (given enough time, it should generate all the prime pairs with difference \$n\$, even if the primes are larger than \$2^{63}\$). However, the probability of generating some output within a reasonable amount of time is close to \$0\$, except if \$(2+n)\$ is prime.
How?
Start with x=2
. If x
and x+n
are both primes, then return (x,x+n)
with probability \$\frac{1}{2}\$. Otherwise, add a random number d
(which can be positive or negative) to x
and repeat.
[2, gap + 2]
wheregap + 2
is prime. \$\endgroup\$