2009-01-07 04:18:00 -05:00
|
|
|
! Copyright (C) 2009 Samuel Tardieu.
|
|
|
|
! See http://factorcode.org/license.txt for BSD license.
|
2009-06-24 07:04:20 -04:00
|
|
|
USING: arrays byte-arrays kernel math math.bitwise math.functions math.order
|
|
|
|
math.ranges sequences sequences.private ;
|
2008-12-26 14:58:46 -05:00
|
|
|
IN: math.primes.erato
|
|
|
|
|
2009-06-24 07:04:20 -04:00
|
|
|
<PRIVATE
|
2008-12-26 14:58:46 -05:00
|
|
|
|
2012-10-23 13:49:45 -04:00
|
|
|
CONSTANT: masks
|
|
|
|
{ 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 }
|
2008-12-26 14:58:46 -05:00
|
|
|
|
2012-10-23 13:49:45 -04:00
|
|
|
: bit-pos ( n -- byte mask/f )
|
|
|
|
30 /mod masks nth-unsafe ; inline
|
2008-12-26 14:58:46 -05:00
|
|
|
|
2009-06-24 07:04:20 -04:00
|
|
|
: marked-unsafe? ( n arr -- ? )
|
2012-08-23 12:35:09 -04:00
|
|
|
[ bit-pos ] dip swap
|
|
|
|
[ [ nth-unsafe ] [ bitand zero? not ] bi* ] [ 2drop f ] if* ; inline
|
2008-12-26 14:58:46 -05:00
|
|
|
|
2009-06-24 07:04:20 -04:00
|
|
|
: unmark ( n arr -- )
|
|
|
|
[ bit-pos swap ] dip
|
2012-10-23 13:49:45 -04:00
|
|
|
pick [ [ swap unmask ] change-nth-unsafe ] [ 3drop ] if ; inline
|
2009-06-24 07:04:20 -04:00
|
|
|
|
2012-08-23 12:35:09 -04:00
|
|
|
: upper-bound ( arr -- n ) length 30 * 1 - ; inline
|
2009-06-24 07:04:20 -04:00
|
|
|
|
|
|
|
: unmark-multiples ( i arr -- )
|
|
|
|
2dup marked-unsafe? [
|
|
|
|
[ [ dup sq ] [ upper-bound ] bi* rot <range> ] keep
|
|
|
|
[ unmark ] curry each
|
|
|
|
] [
|
|
|
|
2drop
|
2012-08-23 12:35:09 -04:00
|
|
|
] if ; inline
|
2009-06-24 07:04:20 -04:00
|
|
|
|
2012-08-23 12:35:09 -04:00
|
|
|
: init-sieve ( n -- arr ) 30 /i 1 + 255 <array> >byte-array ; inline
|
2009-06-24 07:04:20 -04:00
|
|
|
|
|
|
|
PRIVATE>
|
2008-12-26 14:58:46 -05:00
|
|
|
|
|
|
|
: sieve ( n -- arr )
|
2009-06-24 07:04:20 -04:00
|
|
|
init-sieve [ 2 swap upper-bound sqrt [a,b] ] keep
|
|
|
|
[ [ unmark-multiples ] curry each ] keep ;
|
|
|
|
|
|
|
|
: marked-prime? ( n arr -- ? )
|
|
|
|
2dup upper-bound 2 swap between? [ bounds-error ] unless
|
2009-08-11 19:15:53 -04:00
|
|
|
over { 2 3 5 } member? [ 2drop t ] [ marked-unsafe? ] if ;
|