Maximal Prime Gaps
January 8, 2016
Although the prime numbers are fascinating in their own right, sometimes it is interesting and instructive to look at the gaps between successive prime numbers. For instance, here is a table that shows how the maximal prime gap grows:
2 1 3 2 7 4 23 6 89 8 113 14 523 18 887 20
At each step the table shows a prime number and the gap to the next prime number; for instance, at prime 7 the gap to the next prime number, 11, is 4. The table only shows those instances where the prime gap increases. Note that the increases are not steady; for instance, a gap of 14 appears before a gap of 10 or 12.
Your task is to write a program that creates the table shown above. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Let’s try Perl 6 again… The “…” is a lazy sequence…
In Python. primegen is a lazy prime generator and pairwise is from the itertools documentation.
Perl 5, pretty fast (~6 seconds to get to 288).
We could alternately use the simple prime iterator, object prime iterator, or the prime array from that package, but forprimes is the fastest method.
Not part of the exercise, but I will offer a proof that the ascending-prime-gap sequence is infinite.
1. The sequence has at least two terms: 1 and 2. These terms come from the prime gaps (2 => 3) and (3 => 5) respectively.
2. If the sequence has n terms, it also has an (n + 1)th term. Let the nth term be G, with n >= 2. Consider the sequence (G + 2)! + 2, (G + 2)! + 3, (G + 2! + 4, …, (G + 2)! + (G + 2). This sequence has length G + 1, and every term in the sequence is composite (in particular, (G + i)! + i is divislble by i). So there is an (n + 1)th term.
Fun mathematical fact about gaps between primes: if p and q are successive primes (p < q) then q-p-1 is either 0 or 1 or a prime number!
Java Script
==========================================
Result on screen:
2 ; 1
3 ; 2
7 ; 4
23 ; 6
89 ; 8
113 ; 14
523 ; 18
887 ; 20