Files
8th/exercises/practice/sieve/.meta/example.8th
Glenn Jackman d7e5e36502 Create the Sieve of Eratosthenes exercise. (#101)
Also, a script to automate adding new exercises.
2023-09-29 08:22:51 +08:00

54 lines
1.2 KiB
Plaintext

(* from https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_and_variants
*
* algorithm Sieve of Eratosthenes is
* input: an integer n > 1.
* output: all prime numbers from 2 through n.
*
* let A be an array of Boolean values, indexed by integers 2 to n,
* initially all set to true.
*
* for i = 2, 3, 4, ..., not exceeding √n do
* if A[i] is true
* for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n do
* set A[j] := false
*
* return all i such that A[i] is true.
*)
: make-flag-array \ -- a
( drop true ) 0 r@ a:generate
0 false a:!
1 false a:!
;
: mark-multiples-of \ a i -- a
2dup a:@ !if 2drop ;; then
drop
dup dup n:* \ a i idx (initial idx is i^2)
repeat
third over \ a i idx a idx
false a:! \ a i idx a
drop over n:+
dup r@ n:>
until!
2drop
;
: mark-multiples \ a -- a
' mark-multiples-of 2 r@ n:sqrt loop
;
: extract-primes \ a1 -- a2
a:new >r
( if r> a:push >r else drop then ) a:each
drop r>
;
: primes \ n -- a
>r
make-flag-array
mark-multiples
extract-primes
rdrop
;