PageRenderTime 37ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/primality.rkt

http://github.com/huntaub/fractal-math
Racket | 66 lines | 63 code | 3 blank | 0 comment | 10 complexity | 347d2a41812dd386853649e3c6cfdfc0 MD5 | raw file
  1. (require racket/include)
  2. (include "small-primes.rkt")
  3. (define (pow x y) (cond
  4. ((= y 0) 1)
  5. ((= y 1) x)
  6. (else (* x (pow x (- y 1))))))
  7. (define (member? x l)
  8. (cond
  9. ((null? l) #f)
  10. ((equal? (car l) x) #t)
  11. (else (member? x (cdr l)))
  12. ))
  13. (define (l-product a)
  14. (list-product-helper a 0))
  15. (define (list-product-helper a r)
  16. (cond
  17. ((null? a) r)
  18. (else (list-product-helper (cdr a) (* (car a) r)))
  19. ))
  20. (define (prime? n k)
  21. (cond
  22. ((< n 5) (member? n '(2 3)))
  23. ((= (remainder n 2) 0) #f)
  24. (else
  25. (let ((ch (call-helper n)))
  26. (prime-tester k (+ (random (- n 4)) 2) n (cadr (call-helper n)) (car (call-helper n)))))
  27. ))
  28. (define (call-helper n)
  29. (prime-helper 0 (- n 1)))
  30. (define (prime-helper s d)
  31. (cond
  32. ((= (remainder d 2) 0) (prime-helper (+ s 1) (/ d 2)))
  33. (else (list s d))
  34. ))
  35. (define (not-witness a d n s)
  36. (cond
  37. ((= (remainder (pow a d) n) 1) #t)
  38. (else (not-witness-helper s (remainder (pow a d) n) n))
  39. ))
  40. (define (not-witness-helper r x n)
  41. (cond
  42. ((= r 0) #f)
  43. ((= x (- n 1)) #t)
  44. (else (not-witness-helper (- r 1) (remainder (pow x 2) n) n))
  45. ))
  46. (define (prime-tester k a n d s)
  47. (cond
  48. ((> (gcd (+ 2 (random (- n 4))) n) 1) #f)
  49. ((not (not-witness a d n s)) #f)
  50. ((= k 0) #t)
  51. (else (prime-tester (- k 1) a n d s))
  52. ))
  53. (define (gen-prime-helper p)
  54. (let ((k (random (/(- p 1) 2))))
  55. (cond
  56. ((prime? (+ (* 2 k p) 1) 50) (+ (* 2 k p) 1))
  57. (else (gen-prime-helper p))
  58. )))
  59. (define (gen-prime p n)
  60. (cond
  61. ((= n 0) p)
  62. (else (gen-prime (gen-prime-helper p) (- n 1)))
  63. ))