]> gitweb.factorcode.org Git - factor.git/commitdiff
Add Eratosthene sieve as math.primes.erato
authorSamuel Tardieu <sam@rfc1149.net>
Fri, 26 Dec 2008 19:58:46 +0000 (20:58 +0100)
committerSamuel Tardieu <sam@rfc1149.net>
Fri, 26 Dec 2008 19:58:46 +0000 (20:58 +0100)
extra/math/primes/erato/erato-docs.factor [new file with mode: 0644]
extra/math/primes/erato/erato-tests.factor [new file with mode: 0644]
extra/math/primes/erato/erato.factor [new file with mode: 0644]

diff --git a/extra/math/primes/erato/erato-docs.factor b/extra/math/primes/erato/erato-docs.factor
new file mode 100644 (file)
index 0000000..b12ea45
--- /dev/null
@@ -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
diff --git a/extra/math/primes/erato/erato-tests.factor b/extra/math/primes/erato/erato-tests.factor
new file mode 100644 (file)
index 0000000..917824c
--- /dev/null
@@ -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
diff --git a/extra/math/primes/erato/erato.factor b/extra/math/primes/erato/erato.factor
new file mode 100644 (file)
index 0000000..f440903
--- /dev/null
@@ -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