factor/extra/math/primes/primes.factor

52 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 )
dup miller-rabin [ 2 + find-prime-miller-rabin ] unless ; foldable
PRIVATE>
: next-prime ( n -- p )
dup 999983 < [
2008-07-15 18:16:08 -04:00
primes-under-million [ natural-search drop 1+ ] keep nth
2007-12-26 21:59:39 -05:00
] [
next-odd find-prime-miller-rabin
] if ; foldable
: prime? ( n -- ? )
dup 1000000 < [
2008-07-15 18:16:08 -04:00
dup primes-under-million natural-search nip =
2007-12-26 21:59:39 -05:00
] [
miller-rabin
] if ; foldable
: lprimes ( -- list )
0 primes-under-million seq>list
1000003 [ 2 + find-prime-miller-rabin ] lfrom-by
lappend ;
: lprimes-from ( n -- list )
dup 3 < [ drop lprimes ] [ 1- next-prime [ next-prime ] lfrom-by ] if ;
: primes-upto ( n -- seq )
{
{ [ dup 2 < ] [ drop { } ] }
{ [ dup 1000003 < ]
2008-07-15 18:16:08 -04:00
[ primes-under-million [ natural-search drop 1+ 0 swap ] keep <slice> ] }
2008-04-11 13:56:48 -04:00
[ primes-under-million 1000003 lprimes-from
rot [ <= ] curry lwhile list>array append ]
2007-12-26 21:59:39 -05:00
} cond ; foldable
: primes-between ( low high -- seq )
primes-upto
2008-04-04 05:20:10 -04:00
[ 1- next-prime ] dip
2008-07-15 18:16:08 -04:00
[ natural-search drop ] keep [ length ] keep <slice> ; foldable
2008-02-28 00:09:29 -05:00
: coprime? ( a b -- ? ) gcd nip 1 = ; foldable