Skip to main content
4 of 5
Score
orion
  • 3.2k
  • 1
  • 14
  • 16

Calculate prime gaps

Finding primes is a programming rite of passage and very frequently a first serious program someone crates (usually with trial division).

But primes alone are already worn out. A next far more interesting thing is to get the prime gaps: the so-far-longest gaps between consecutive primes. These are quite rare and "precious". A first few pairs and their differences are:

2 3 1
3 5 2
7 11 4
23 29 6
89 97 8
113 127 14
...

My father used to calculate these by hand for fun up to 10k. Let's see how short a code you can get.

Rules:

  • no builtin functions for prime testing, prime generation or prime gaps
  • no retrieving http://oeis.org/A002386 or similar (I can smell you cheaters from far away :) )
  • no precomputed arrays
  • keep printing until your internal integer type fails on you

Lowest character count wins. +10 characters if you only print the gaps without the primes.

You can also show off versions with builtin functions if they are interesting. Be creative.

Clarification: you go through primes and you report every time you see a gap that is bigger than any gap that you have seen before. For instance, between 3 and 5, there is a gap 2 units wide. The gap between 5 and 7 is also 2, but that's old news, we don't care any more. Only when you see a new biggest gap, you report it. This reflects how the primes are getting less and less frequent, as the gaps become wider and wider.


EDIT: Most of the answers are brilliant and deserve more recognition. However, so far, a GolfScript entry with 48 characters is the shortest.

orion
  • 3.2k
  • 1
  • 14
  • 16