factor/basis/math/primes/miller-rabin/miller-rabin.factor

36 lines
841 B
Factor
Raw Normal View History

! Copyright (c) 2008-2009 Doug Coleman.
2008-10-03 03:19:03 -04:00
! See http://factorcode.org/license.txt for BSD license.
USING: combinators combinators.short-circuit kernel locals math
math.functions math.ranges random sequences sets ;
2009-05-10 13:24:43 -04:00
IN: math.primes.miller-rabin
2007-09-20 18:09:08 -04:00
<PRIVATE
:: (miller-rabin) ( n trials -- ? )
n 1 - :> n-1
n-1 factor-2s :> ( r s )
0 :> a!
2010-01-14 10:10:13 -05:00
trials iota [
2009-05-06 13:21:30 -04:00
drop
2 n 2 - [a,b] random a!
a s n ^mod 1 = [
2009-05-06 13:21:30 -04:00
f
] [
r iota [
2^ s * a swap n ^mod n - -1 =
] any? not
2009-05-06 13:21:30 -04:00
] if
] any? not ;
PRIVATE>
2007-09-20 18:09:08 -04:00
: miller-rabin* ( n numtrials -- ? )
over {
{ [ dup 1 <= ] [ 3drop f ] }
{ [ dup 2 = ] [ 3drop t ] }
2008-01-13 01:07:49 -05:00
{ [ dup even? ] [ 3drop f ] }
[ drop (miller-rabin) ]
2007-09-20 18:09:08 -04:00
} cond ;
: miller-rabin ( n -- ? ) 10 miller-rabin* ;