PageRenderTime 146ms CodeModel.GetById 16ms app.highlight 81ms RepoModel.GetById 1ms app.codeStats 45ms

/primality.rkt

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