math.primes.erato.fast: adding fast Sieve of Eratosthenes.

db4
John Benediktsson 2015-06-15 19:51:02 -07:00
parent 588a05bc62
commit db42e12853
4 changed files with 66 additions and 0 deletions

View File

@ -0,0 +1 @@
John Benediktsson

View File

@ -0,0 +1,14 @@
USING: sequences tools.test ;
IN: math.primes.erato.fast
{
V{
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
73 79 83 89 97
}
} [ 100 sieve ] unit-test
{ 1229 } [ 10,000 sieve length ] unit-test
{ 9592 } [ 100,000 sieve length ] unit-test
{ 78498 } [ 1,000,000 sieve length ] unit-test

View File

@ -0,0 +1,50 @@
! Copyright (C) 2015 John Benediktsson
! See http://factorcode.org/license.txt for BSD license
USING: bit-arrays fry kernel kernel.private locals math
math.functions math.private sequences sequences.private ;
IN: math.primes.erato.fast
<PRIVATE
CONSTANT: wheel-2-3-5-7 B{
2 4 2 4 6 2 6 4 2 4 6 6 2 6 4 2 6 4 6 8 4 2 4 2 4 8 6 4 6 2
4 6 2 6 6 4 2 4 6 2 6 4 2 4 2 10 2 10
}
:: each-prime ( upto sieve quot -- )
11 upto >fixnum '[ dup _ <= ] [
wheel-2-3-5-7 [
over dup 2/ sieve nth-unsafe [ drop ] quot if
fixnum+fast
] each
] while drop ; inline
:: mark-multiples ( i upto sieve -- )
i 2 fixnum*fast :> step
i i fixnum*fast upto >fixnum '[ dup _ <= ] [
t over 2/ sieve set-nth-unsafe
step fixnum+fast
] while drop ; inline
: sieve-bits ( n -- bits )
210 /i 1 + 210 * 2/ 6 + ; inline
PRIVATE>
:: make-sieve ( n -- sieve )
n sieve-bits <bit-array> :> sieve
t 0 sieve set-nth
t 4 sieve set-nth
n sqrt sieve [ n sieve mark-multiples ] each-prime
sieve ; inline
:: sieve ( n -- primes )
V{ 2 3 5 7 } clone :> primes
n dup make-sieve [
dup n <= [ primes push ] [ drop ] if
] each-prime primes ;
:: sieve-prime? ( i sieve -- prime? )
i even? [ f ] [ i 2/ sieve nth ] if ;

View File

@ -0,0 +1 @@
Eratosthene sieve (fast!)