-
Notifications
You must be signed in to change notification settings - Fork 0
/
prime.scm
executable file
·38 lines (34 loc) · 969 Bytes
/
prime.scm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
(define (square n)
(* n n))
(define (expmod base exp m)
(cond ((= exp 0) 1)
((even? exp)
(remainder (square (expmod base (/ exp 2) m))
m))
(else
(remainder (* base (expmod base (- exp 1) m))
m))))
(define (fermat-test n times)
(define (test n)
(let ((a (random (- n 1))))
(= (expmod a n n) a)))
(cond ((= times 0) true)
((test n) (fermat-test n (- times 1)))
(else false)))
(define (divides? a b)
(= (remainder b a) 0))
(define (smallest-divisor n)
(define (find-divisor n test-divisor)
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (+ test-divisor 1)))))
(find-divisor n 2))
(define (real-prime? n)
(= (smallest-divisor n) n))
(define (prime? n)
(fermat-test n 100))
(define (tp n)
(display (prime? n))
(display "\n")
(display (real-prime? n)))
(tp 1105)