1 ! Copyright (C) 2009 Samuel Tardieu.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel kernel.private math math.bitwise
4 math.functions math.order math.private ranges sequences
10 ! This is a compressed Sieve of Eratosthenes that uses the
11 ! 2-3-5 wheel to check groups of 8 candidates starting with
12 ! { 1 7 11 13 17 19 23 29 } allowing us to use a byte-array
13 ! to store each group of booleans in a byte.
16 { f 128 f f f f f 64 f f f 32 f 16 f f f 8 f 4 f f f 2 f f f f f 1 }
18 : bit-pos ( n -- byte mask/f )
20 30 /mod masks nth-unsafe
21 { maybe{ fixnum } } declare ; inline
23 :: marked-unsafe? ( n sieve -- ? )
25 [ sieve nth-unsafe ] [ mask zero? not ] bi*
26 ] [ drop f ] if* ; inline
28 :: unmark ( n sieve -- )
30 swap sieve [ swap unmask ] change-nth-unsafe
31 ] [ drop ] if* ; inline
33 : upper-bound ( sieve -- n ) length 30 * 1 - ; inline
35 :: unmark-multiples ( i upper sieve -- )
36 i 2 fixnum*fast :> step
39 [ sieve unmark ] [ step fixnum+fast ] bi
42 : init-sieve ( n -- sieve )
43 30 /i 1 + [ 255 ] B{ } replicate-as ; inline
47 :: sieve ( n -- sieve )
48 n integer>fixnum-strict init-sieve :> sieve
49 sieve upper-bound >fixnum :> upper
50 3 upper sqrt 2 <range> [| i |
51 i sieve marked-unsafe? [
52 i upper sieve unmark-multiples
56 : marked-prime? ( n sieve -- ? )
57 [ integer>fixnum-strict ] dip
58 2dup upper-bound 2 swap between? [ bounds-error ] unless
59 over { 2 3 5 } member? [ 2drop t ] [ marked-unsafe? ] if ;