1 ! Copyright (C) 2015 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
4 USING: bit-arrays fry kernel kernel.private locals math
5 math.functions math.private sequences sequences.private ;
7 IN: math.primes.erato.fast
11 CONSTANT: wheel-2-3-5-7 B{
12 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
13 4 6 2 6 6 4 2 4 6 2 6 4 2 4 2 10 2 10
16 :: each-prime ( upto sieve quot -- )
17 11 upto >fixnum '[ dup _ <= ] [
19 over dup 2/ sieve nth-unsafe [ drop ] quot if
24 :: mark-multiples ( i upto sieve -- )
25 i 2 fixnum*fast :> step
26 i i fixnum*fast upto >fixnum '[ dup _ <= ] [
27 t over 2/ sieve set-nth-unsafe
31 : sieve-bits ( n -- bits )
32 210 /i 1 + 210 * 2/ 6 + ; inline
36 :: make-sieve ( n -- sieve )
37 n sieve-bits <bit-array> :> sieve
40 n sqrt sieve [ n sieve mark-multiples ] each-prime
43 :: sieve ( n -- primes )
44 V{ 2 3 5 7 } clone :> primes
46 dup n <= [ primes push ] [ drop ] if
49 :: sieve-prime? ( i sieve -- prime? )
50 i even? [ f ] [ i 2/ sieve nth ] if ;