]> gitweb.factorcode.org Git - factor.git/blob - basis/math/primes/miller-rabin/miller-rabin.factor
factor: trim using lists
[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 kernel math math.functions ranges
4 random sequences ;
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 <iota> [
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             ] none?
22         ] if
23     ] none? ;
24
25 PRIVATE>
26
27 : miller-rabin* ( n numtrials -- ? )
28     {
29         { [ over 1 <= ] [ 2drop f ] }
30         { [ over even? ] [ drop 2 = ] }
31         [ (miller-rabin) ]
32     } cond ;
33
34 : miller-rabin ( n -- ? ) 10 miller-rabin* ;