{ { 999983 1000003 } } [ 2 999982 lprimes-from ltake list>array ] unit-test
{ { 2 3 5 7 } } [ 10 primes-upto >array ] unit-test
{ { 999983 1000003 } } [ 999982 1000010 primes-between >array ] unit-test
+
+{ { 4999963 4999999 5000011 5000077 5000081 } }
+[ 4999962 5000082 primes-between >array ]
+unit-test
! Copyright (C) 2007 Samuel Tardieu.
! See http://factorcode.org/license.txt for BSD license.
USING: binary-search combinators kernel lists.lazy math math.functions
- math.miller-rabin math.primes.list sequences ;
+math.miller-rabin math.primes.erato math.ranges sequences ;
IN: math.primes
<PRIVATE
-: find-prime-miller-rabin ( n -- p )
- [ dup miller-rabin ] [ 2 + ] [ ] until ; foldable
+: look-in-bitmap ( n -- ? ) >index 4999999 sieve nth ;
-PRIVATE>
+: really-prime? ( n -- ? )
+ dup 5000000 < [ look-in-bitmap ] [ miller-rabin ] if ; foldable
-: next-prime ( n -- p )
- dup 999983 < [
- primes-under-million [ natural-search drop 1+ ] keep nth
- ] [
- next-odd find-prime-miller-rabin
- ] if ; foldable
+PRIVATE>
: prime? ( n -- ? )
- dup 1000000 < [
- dup primes-under-million natural-search nip =
- ] [
- miller-rabin
- ] if ; foldable
+ {
+ { [ dup 2 < ] [ drop f ] }
+ { [ dup even? ] [ 2 = ] }
+ [ really-prime? ]
+ } cond ; foldable
+
+: next-prime ( n -- p )
+ next-odd [ dup really-prime? ] [ 2 + ] [ ] until ; foldable
-: lprimes ( -- list )
- 0 primes-under-million seq>list
- 1000003 [ 2 + find-prime-miller-rabin ] lfrom-by
- lappend ;
+: lprimes ( -- list ) 2 [ next-prime ] lfrom-by ;
: 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 < ] [
- primes-under-million [ natural-search drop 1+ 0 swap ] keep <slice>
- ] }
- [ lprimes swap [ <= ] curry lwhile list>array ]
- } cond ; foldable
+ dup 2 < [
+ drop V{ }
+ ] [
+ 3 swap 2 <range> [ prime? ] filter 2 prefix
+ ] if ; foldable
: primes-between ( low high -- seq )
primes-upto [ 1- next-prime ] dip