Created
February 2, 2022 00:15
-
-
Save sato11/214974f33d7d6197447b94661d0a73bd to your computer and use it in GitHub Desktop.
Probablistic primality test based on SICP 1.2.6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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) | |
(define (try-it a) | |
(= (expmod a n n) a)) | |
(try-it (+ 1 (random (- n 1))))) | |
(define (carmichael-test n) | |
(define (iter a n) | |
(cond ((= a n) #t) | |
((= (expmod a n n) a) (iter (+ a 1) n)) | |
(else #f))) | |
(iter 1 n)) | |
(define (miller-rabin-test n) | |
(define (miller-rabin-expmod base exp m) | |
(define (squaremod-with-check x) | |
(define (check-nontrivial-sqrt1 x square) | |
(if (and (= square 1) | |
(not (= x 1)) | |
(not (= x (- m 1)))) | |
0 | |
square)) | |
(check-nontrivial-sqrt1 x (remainder (square x) m))) | |
(cond ((= exp 0) 1) | |
((even? exp) (squaremod-with-check (miller-rabin-expmod base | |
(/ exp 2) | |
m))) | |
(else | |
(remainder (* base (miller-rabin-expmod base | |
(- exp 1) | |
m)) | |
m)))) | |
(define (try-it a) | |
(= | |
(miller-rabin-expmod a | |
(- n 1) | |
n) | |
1)) | |
(try-it (+ 1 (random (- n 1))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment