1 ! Copyright (c) 2007 Samuel Tardieu.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors bit-arrays fry kernel lists.lazy math math.functions
4 math.primes.list math.ranges sequences ;
9 TUPLE: erato limit bits latest ;
14 : is-prime ( n limit -- bool )
15 [ ind ] [ bits>> ] bi* nth ; inline
17 : indices ( n erato -- range )
18 limit>> ind over 3 * ind spin <range> ;
20 : mark-multiples ( n erato -- )
21 2dup [ sq ] [ limit>> ] bi* <= [
22 [ indices ] keep bits>> '[ _ f -rot set-nth ] each
25 : <erato> ( n -- erato )
26 dup ind 1+ <bit-array> dup set-bits 1 erato boa ;
28 : next-prime ( erato -- prime/f )
29 [ 2 + ] change-latest [ latest>> ] keep
31 2dup is-prime [ dupd mark-multiples ] [ nip next-prime ] if
38 : lerato ( n -- lazy-list )
40 0 primes-under-million seq>list swap '[ _ <= ] lwhile
42 <erato> 2 [ drop next-prime ] with lfrom-by [ ] lwhile