Twin primes
Posted: Wed Aug 28, 2019 2:14 pm
Two functions to calculate twin primes (pairs and pairs-i).
Post yours :-)
Code: Select all
(define (prime? n)
(if (even? n) nil
(= 1 (length (factor n)))))
(define (twin? n)
(if (and (prime? n) (prime? (+ n 2)))
(list n (+ n 2))
nil))
(twin? 9)
;-> nil
(twin? 881)
;-> (881 883)
(define (pairs a b)
(filter true? (map twin? (sequence a b))))
(pairs 3 1000)
;-> ((3 5) (5 7) (11 13) (17 19) (29 31) (41 43) (59 61) (71 73) (101 103) (107 109)
;-> (137 139) (149 151) (179 181) (191 193) (197 199) (227 229) (239 241) (269 271)
;-> (281 283) (311 313) (347 349) (419 421) (431 433) (461 463) (521 523) (569 571)
;-> (599 601) (617 619) (641 643) (659 661) (809 811) (821 823) (827 829) (857 859)
;-> (881 883))
(length (pairs 3 1000))
;-> 35
(time (pairs 3 2e7))
;-> 47479.457
==================================================
(define (pairs-i a b)
(local (idx found out)
(setq found nil)
(setq idx a)
; only the number 5 belongs to two pairs of twin prime numbers
(setq out '((3 5) (5 7)))
(while (< idx b)
(if (and (prime? idx) (prime? (+ idx 2)))
(begin
(push (list idx (+ idx 2)) out -1)
(setq found true))
)
(if found (++ idx 4) (++ idx 2))
(setq found nil)
)
out
)
)
(pairs-i 7 1000)
;-> ((3 5) (5 7) (11 13) (17 19) (29 31) (41 43) (59 61) (71 73) (101 103) (107 109)
;-> (137 139) (149 151) (179 181) (191 193) (197 199) (227 229) (239 241) (269 271)
;-> (281 283) (311 313) (347 349) (419 421) (431 433) (461 463) (521 523) (569 571)
;-> (599 601) (617 619) (641 643) (659 661) (809 811) (821 823) (827 829) (857 859)
;-> (881 883))
(length (pairs-i 7 1000))
;-> 35
(time (pairs-i 7 2e7))
;-> 43177.908