factor/extra/math/erato/erato.factor

44 lines
1.0 KiB
Factor
Raw Normal View History

! Copyright (c) 2007 Samuel Tardieu.
! See http://factorcode.org/license.txt for BSD license.
USING: bit-arrays kernel lists.lazy math math.functions math.primes.list
2008-08-31 03:52:11 -04:00
math.ranges sequences accessors ;
IN: math.erato
2007-12-21 18:28:46 -05:00
<PRIVATE
TUPLE: erato limit bits latest ;
2007-12-21 18:28:46 -05:00
: ind ( n -- i )
2/ 1- ; inline
2007-12-21 18:28:46 -05:00
: is-prime ( n erato -- bool )
2008-08-31 03:52:11 -04:00
>r ind r> bits>> nth ; inline
2007-12-21 18:28:46 -05:00
: indices ( n erato -- range )
2008-08-31 03:52:11 -04:00
limit>> ind over 3 * ind swap rot <range> ;
2007-12-21 18:28:46 -05:00
: mark-multiples ( n erato -- )
2008-08-31 03:52:11 -04:00
over sq over limit>> <=
[ [ indices ] keep bits>> [ f -rot set-nth ] curry each ] [ 2drop ] if ;
: <erato> ( n -- erato )
dup ind 1+ <bit-array> 1 over set-bits erato boa ;
: next-prime ( erato -- prime/f )
2008-08-31 03:52:11 -04:00
[ 2 + ] change-latest [ latest>> ] keep
2dup limit>> <=
[
2007-12-21 18:28:46 -05:00
2dup is-prime [ dupd mark-multiples ] [ nip next-prime ] if
] [
2drop f
] if ;
2007-12-21 18:28:46 -05:00
PRIVATE>
: lerato ( n -- lazy-list )
dup 1000003 < [
0 primes-under-million seq>list swap [ <= ] curry lwhile
] [
2008-01-09 17:36:30 -05:00
<erato> 2 [ drop next-prime ] with lfrom-by [ ] lwhile
] if ;