Last active
June 2, 2016 22:22
-
-
Save cky/ac11c20816b41f82c13bb59bb173cbad to your computer and use it in GitHub Desktop.
My Miller-Rabin implementation (see http://codereview.stackexchange.com/a/129991/216 for context)
This file contains hidden or 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
#lang racket | |
(define (expmod base exp m) | |
(let recur ([exp exp]) | |
(cond [(zero? exp) 1] | |
[(even? exp) (let* ([prev (recur (quotient exp 2))] | |
[result (modulo (sqr prev) m)]) | |
(if (and (< 1 prev (sub1 m)) | |
(= result 1)) | |
0 | |
result))] | |
[else (modulo (* base (recur (sub1 exp))) m)]))) | |
(define (composite? n [trials 100]) | |
(for/first ([i (in-range trials)] | |
#:unless (= (expmod (random 2 (min (sub1 n) 4294967087)) | |
(sub1 n) n) 1)) | |
#t)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
BTW, the
(min (sub1 n) 4294967087)
, as opposed to just(sub1 n)
, is to preventrandom
from issuing a domain error.