1 ! Copyright (C) 2015 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
4 USING: bit-arrays kernel literals math math.functions
5 math.private ranges math.statistics sequences
8 IN: math.primes.erato.fast
12 CONSTANT: wheel-2-3-5-7 $[
14 { 2 3 5 7 } [ divisor? ] with none?
15 ] B{ } filter-as differences
18 :: each-prime ( upto sieve quot -- )
19 11 upto integer>fixnum-strict '[ dup _ <= ] [
21 over dup 2/ sieve nth-unsafe [ drop ] quot if
26 :: mark-multiples ( i upto sieve -- )
27 i 2 fixnum*fast :> step
28 i i fixnum*fast upto integer>fixnum-strict '[ dup _ <= ] [
29 t over 2/ sieve set-nth-unsafe
33 : sieve-bits ( n -- bits )
34 210 /i 1 + 210 * 2/ 6 + ; inline
38 :: make-sieve ( n -- sieve )
39 n sieve-bits <bit-array> :> sieve
43 [ n sieve mark-multiples ] each-prime
46 :: sieve ( n -- primes )
47 V{ 2 3 5 7 } clone :> primes
49 dup n <= [ primes push ] [ drop ] if
52 :: marked-prime? ( i sieve -- prime? )
53 i dup even? [ 2 = ] [ 2/ sieve nth not ] if ;