Add Eratosthene sieve as math.primes.erato
parent
7716ac276e
commit
93b20967b5
|
@ -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
|
|
@ -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
|
|
@ -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
|
Loading…
Reference in New Issue