]> gitweb.factorcode.org Git - factor.git/blob - basis/math/primes/erato/erato.factor
math.primes.erato: minor performance improvements.
[factor.git] / basis / math / primes / erato / erato.factor
1 ! Copyright (C) 2009 Samuel Tardieu.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: arrays byte-arrays kernel math math.bitwise math.functions math.order
4 math.ranges sequences sequences.private ;
5 IN: math.primes.erato
6
7 <PRIVATE
8
9 CONSTANT: masks
10 { 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 }
11
12 : bit-pos ( n -- byte mask/f )
13     30 /mod masks nth-unsafe ; inline
14
15 : marked-unsafe? ( n arr -- ? )
16     [ bit-pos ] dip swap
17     [ [ nth-unsafe ] [ bitand zero? not ] bi* ] [ 2drop f ] if* ; inline
18
19 : unmark ( n arr -- )
20     [ bit-pos swap ] dip
21     pick [ [ swap unmask ] change-nth-unsafe ] [ 3drop ] if ; inline
22
23 : upper-bound ( arr -- n ) length 30 * 1 - ; inline
24
25 : unmark-multiples ( i arr -- )
26     2dup marked-unsafe? [
27         [ [ dup sq ] [ upper-bound ] bi* rot <range> ] keep
28         [ unmark ] curry each
29     ] [
30         2drop
31     ] if ; inline
32
33 : init-sieve ( n -- arr ) 30 /i 1 + 255 <array> >byte-array ; inline
34
35 PRIVATE>
36
37 : sieve ( n -- arr )
38     init-sieve [ 2 swap upper-bound sqrt [a,b] ] keep
39     [ [ unmark-multiples ] curry each ] keep ;
40
41 : marked-prime? ( n arr -- ? )
42     2dup upper-bound 2 swap between? [ bounds-error ] unless
43     over { 2 3 5 } member? [ 2drop t ] [ marked-unsafe? ] if ;