factor/extra/math/primes/primes.factor

43 lines
1.1 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.
2008-11-08 16:34:39 -05:00
USING: binary-search combinators kernel lists.lazy math math.functions
math.miller-rabin math.primes.erato math.ranges sequences ;
2007-12-26 21:59:39 -05:00
IN: math.primes
<PRIVATE
: look-in-bitmap ( n -- ? ) >index 4999999 sieve nth ;
2007-12-26 21:59:39 -05:00
: really-prime? ( n -- ? )
dup 5000000 < [ look-in-bitmap ] [ miller-rabin ] if ; foldable
2007-12-26 21:59:39 -05:00
PRIVATE>
2007-12-26 21:59:39 -05:00
: prime? ( n -- ? )
{
{ [ dup 2 < ] [ drop f ] }
{ [ dup even? ] [ 2 = ] }
[ really-prime? ]
} cond ; foldable
: next-prime ( n -- p )
next-odd [ dup really-prime? ] [ 2 + ] [ ] until ; foldable
2007-12-26 21:59:39 -05:00
: lprimes ( -- list ) 2 [ next-prime ] lfrom-by ;
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 )
dup 2 < [
drop V{ }
] [
3 swap 2 <range> [ prime? ] filter 2 prefix
] if ; foldable
2007-12-26 21:59:39 -05:00
: primes-between ( low high -- seq )
2008-11-08 16:34:39 -05:00
primes-upto [ 1- next-prime ] dip
[ natural-search drop ] [ length ] [ ] tri <slice> ; foldable
2008-02-28 00:09:29 -05:00
: coprime? ( a b -- ? ) gcd nip 1 = ; foldable