Add Eratosthene sieve as math.primes.erato

db4
Samuel Tardieu 2008-12-26 20:58:46 +01:00
parent 7716ac276e
commit 93b20967b5
3 changed files with 38 additions and 0 deletions

View File

@ -0,0 +1,12 @@
USING: help.markup help.syntax ;
IN: math.primes.erato
HELP: sieve
{ $values { "n" "the greatest odd number to consider" } { "arr" "a bit array" } }
{ $description "Return a bit array containing a primality bit for every odd number between 3 and " { $snippet "n" } " (inclusive). " { $snippet ">index" } " can be used to retrieve the index of an odd number to be tested." } ;
HELP: >index
{ $values { "n" "an odd number" } { "i" "the corresponding index" } }
{ $description "Retrieve the index corresponding to the odd number on the stack." } ;
{ sieve >index } related-words

View File

@ -0,0 +1,3 @@
USING: bit-arrays math.primes.erato tools.test ;
[ ?{ t t t f t t f t t f t f f t } ] [ 29 sieve ] unit-test

View File

@ -0,0 +1,23 @@
USING: bit-arrays kernel math math.functions math.ranges sequences ;
IN: math.primes.erato
: >index ( n -- i )
3 - 2 /i ; inline
: index> ( i -- n )
2 * 3 + ; inline
: mark-multiples ( i arr -- )
[ dup index> [ + ] keep ] dip
[ length 1 - swap <range> f swap ] keep
[ set-nth ] curry with each ;
: maybe-mark-multiples ( i arr -- )
2dup nth [ mark-multiples ] [ 2drop ] if ;
: init-sieve ( n -- arr )
>index 1 + <bit-array> dup set-bits ;
: sieve ( n -- arr )
[ init-sieve ] [ sqrt >index [0,b] ] bi
over [ maybe-mark-multiples ] curry each ; foldable