Prime Gaps
February 2, 2016
We reuse the primegen
infrastructure from the previous exercise. Then gaps
finds the prime gaps less than n:
(define (gaps n) (let ((ps (primegen)) (gs (make-hashtable identity =))) (let* ((prev (ps)) (prev (ps)) (curr (ps))) (let loop ((prev prev) (curr curr) (len 0)) (cond ((= n len) (do ((g 2 (+ g 2))) ((< n g)) (display g) (display #\tab) (display (hashtable-ref gs g #f)) (newline))) ((hashtable-contains? gs (- curr prev)) (loop curr (ps) len)) (else (hashtable-set! gs (- curr prev) prev) (loop curr (ps) (+ len 1))))))))
Here’s what it looks like in action:
> (gaps 50) 2 3 4 7 6 23 8 89 10 139 12 199 14 113 16 1831 18 523 20 887 22 1129 24 1669 26 2477 28 2971 30 4297 32 5591 34 1327 36 9551 38 30593 40 19333 42 16141 44 15683 46 81463 48 28229 50 31907
You can see the program at http://ideone.com/i8LT12, though it won’t run because Guile doesn’t implement R6RS-style hash tables.
In Python:
Correction, prime generator should be initiated inside the [for gap] loop.
A perl 6 version – keeps track of higher gaps until they need to be displayed!
In Python. Using a dict to record the minimal gaps. The prime generator can be initialized once outside the main loop. The function pairwise is from the itertools doc and lazyprime is from an earlier exercise.