factor/extra/math/primes/primes.factor

53 lines
1.4 KiB
Factor
Raw Normal View History

2007-12-26 21:59:39 -05:00
! Copyright (C) 2007 Samuel Tardieu.
! See http://factorcode.org/license.txt for BSD license.
USING: combinators kernel lists.lazy math math.functions math.miller-rabin
2008-07-15 18:16:08 -04:00
math.order math.primes.list math.ranges sequences sorting
binary-search ;
2007-12-26 21:59:39 -05:00
IN: math.primes
<PRIVATE
: find-prime-miller-rabin ( n -- p )
2008-10-03 03:19:03 -04:00
dup miller-rabin [ 2 + find-prime-miller-rabin ] unless ; foldable
2007-12-26 21:59:39 -05:00
PRIVATE>
: next-prime ( n -- p )
2008-10-03 03:19:03 -04:00
dup 999983 < [
primes-under-million [ natural-search drop 1+ ] keep nth
] [
next-odd find-prime-miller-rabin
] if ; foldable
2007-12-26 21:59:39 -05:00
: prime? ( n -- ? )
2008-10-03 03:19:03 -04:00
dup 1000000 < [
dup primes-under-million natural-search nip =
] [
miller-rabin
] if ; foldable
2007-12-26 21:59:39 -05:00
: lprimes ( -- list )
2008-10-03 03:19:03 -04:00
0 primes-under-million seq>list
1000003 [ 2 + find-prime-miller-rabin ] lfrom-by
lappend ;
2007-12-26 21:59:39 -05:00
: lprimes-from ( n -- list )
2008-10-03 03:19:03 -04:00
dup 3 < [ drop lprimes ] [ 1- next-prime [ next-prime ] lfrom-by ] if ;
2007-12-26 21:59:39 -05:00
: primes-upto ( n -- seq )
2008-10-03 03:19:03 -04:00
{
{ [ dup 2 < ] [ drop { } ] }
{ [ dup 1000003 < ] [
primes-under-million [ natural-search drop 1+ 0 swap ] keep <slice>
] }
[ primes-under-million 1000003 lprimes-from
rot [ <= ] curry lwhile list>array append ]
} cond ; foldable
2007-12-26 21:59:39 -05:00
: primes-between ( low high -- seq )
2008-10-03 03:19:03 -04:00
primes-upto
[ 1- next-prime ] dip
[ natural-search drop ] keep [ length ] keep <slice> ; foldable
2008-02-28 00:09:29 -05:00
: coprime? ( a b -- ? ) gcd nip 1 = ; foldable