]> gitweb.factorcode.org Git - factor.git/blob - basis/math/primes/miller-rabin/miller-rabin.factor
04b1330cc2e0bec710355bf32b387d812a28fa5f
[factor.git] / basis / math / primes / miller-rabin / miller-rabin.factor
1 ! Copyright (c) 2008-2009 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: combinators combinators.short-circuit kernel locals math
4 math.functions math.ranges random sequences sets ;
5 IN: math.primes.miller-rabin
6
7 <PRIVATE
8
9 :: (miller-rabin) ( n trials -- ? )
10     n 1 - :> n-1
11     n-1 factor-2s :> ( r s )
12     0 :> a!
13     trials [
14         drop
15         2 n 2 - [a,b] random a!
16         a s n ^mod 1 = [
17             f
18         ] [
19             r iota [
20                 2^ s * a swap n ^mod n - -1 =
21             ] any? not
22         ] if
23     ] any? not ;
24
25 PRIVATE>
26
27 : miller-rabin* ( n numtrials -- ? )
28     over {
29         { [ dup 1 <= ] [ 3drop f ] }
30         { [ dup 2 = ] [ 3drop t ] }
31         { [ dup even? ] [ 3drop f ] }
32         [ drop (miller-rabin) ]
33     } cond ;
34
35 : miller-rabin ( n -- ? ) 10 miller-rabin* ;