factor/extra/math/erato/erato.factor

44 lines
1.1 KiB
Factor
Raw Normal View History

! Copyright (c) 2007 Samuel Tardieu.
! See http://factorcode.org/license.txt for BSD license.
2008-11-07 01:24:32 -05:00
USING: accessors bit-arrays fry kernel lists.lazy math math.functions
math.primes.list math.ranges sequences ;
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 )
2008-11-07 01:24:32 -05:00
2/ 1- ; inline
2008-10-03 03:19:03 -04:00
: is-prime ( n limit -- bool )
2008-11-07 01:24:32 -05:00
[ ind ] [ bits>> ] bi* nth ; inline
2007-12-21 18:28:46 -05:00
: indices ( n erato -- range )
2008-11-08 15:30:28 -05:00
limit>> ind over 3 * ind spin <range> ;
2007-12-21 18:28:46 -05:00
: mark-multiples ( n erato -- )
2008-11-07 01:24:32 -05:00
2dup [ sq ] [ limit>> ] bi* <= [
[ indices ] keep bits>> '[ _ f -rot set-nth ] each
] [ 2drop ] if ;
: <erato> ( n -- erato )
2008-11-07 01:24:32 -05:00
dup ind 1+ <bit-array> dup set-bits 1 erato boa ;
: next-prime ( erato -- prime/f )
2008-11-07 01:24:32 -05:00
[ 2 + ] change-latest [ latest>> ] keep
2dup limit>> <= [
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 )
2008-11-07 01:24:32 -05:00
dup 1000003 < [
0 primes-under-million seq>list swap '[ _ <= ] lwhile
] [
<erato> 2 [ drop next-prime ] with lfrom-by [ ] lwhile
] if ;