New math.erato library: sieve of Eratosthene

db4
Samuel Tardieu 2007-12-21 13:03:59 +01:00
parent d5cd2fd66b
commit 074ef1e107
5 changed files with 56 additions and 0 deletions

View File

@ -0,0 +1 @@
Samuel Tardieu

View File

@ -0,0 +1,14 @@
USING: help.markup help.syntax ;
IN: math.erato
HELP: <erato>
{ $values { "n" "a positive number" } { "erato" "a prime numbers generator" } }
{ $description "Build a prime numbers generator for primes between 2 and " { $snippet "n" } " (inclusive)." } ;
HELP: next-prime
{ $values { "erato" "a generator" } { "prime/f" "a prime number or f" } }
{ $description "Compute the next prime number using the given generator. If there are no more prime numbers under the limit used when building the generator, f is returned instead." } ;
HELP: lerato
{ $values { "n" "a positive number" } { "lazy-list" "a lazy prime numbers generator" } }
{ $description "Builds a lazy list containing the prime numbers between 2 and " { $snippet "n" } " (inclusive). Lazy lists are described in " { $link "lazy-lists" } "." } ;

View File

@ -0,0 +1,6 @@
! Copyright (c) 2007 Samuel Tardieu.
! See http://factorcode.org/license.txt for BSD license.
USING: lazy-lists math.erato tools.test ;
IN: temporary
[ { 2 3 5 7 11 13 17 19 } ] [ 20 lerato list>array ] unit-test

View File

@ -0,0 +1,34 @@
! Copyright (c) 2007 Samuel Tardieu.
! See http://factorcode.org/license.txt for BSD license.
USING: bit-arrays kernel lazy-lists math math.functions math.ranges sequences ;
IN: math.erato
TUPLE: erato limit bits latest ;
<PRIVATE
: mark-multiples ( n erato -- )
over sqrt over erato-limit <=
[
[ erato-limit over <range> ] keep
erato-bits [ set-nth ] curry f -rot curry* each
] [
2drop
] if ;
PRIVATE>
: <erato> ( n -- erato )
dup 1 + <bit-array> 1 over set-bits erato construct-boa ;
: next-prime ( erato -- prime/f )
[ erato-latest 1+ ] keep [ set-erato-latest ] 2keep
2dup erato-limit <=
[
2dup erato-bits nth [ dupd mark-multiples ] [ nip next-prime ] if
] [
2drop f
] if ;
: lerato ( n -- lazy-list )
<erato> [ next-prime ] keep [ nip next-prime ] curry lfrom-by [ ] lwhile ;

View File

@ -0,0 +1 @@
Sieve of Eratosthene