Sieve of Eratosthenes: Difference between revisions

m
add consistency to examples
m (add consistency to examples)
Line 11,853:
===Functional===
<lang ocaml>(* first define some iterators *)
# let fold_iter f init a b =
let rec aux acc i =
if i > b
then (acc)
else aux (f acc i) (succ i)
in
aux init a ;;
(* val fold_iter : ('a -> int -> 'a) -> 'a -> int -> int -> 'a = <fun>*)
 
# let fold_step f init a b step =
let rec aux acc i =
if i > b
then (acc)
else aux (f acc i) (i + step)
in
aux init a ;;
(* val fold_step : ('a -> int -> 'a) -> 'a -> int -> int -> int -> 'a = <fun>*)
 
(* remove a given value from a list *)
# let remove li v =
let rec aux acc = function
| hd::tl when hd = v -> (List.rev_append acc tl)
| hd::tl -> aux (hd::acc) tl
| [] -> li
in
aux [] li ;;
(* val remove : 'a list -> 'a -> 'a list = <fun>*)
 
(* the main function *)
# let primes n =
let li =
(* create a list [from 2; ... until n] *)
List.rev(fold_iter (fun acc i -> (i::acc)) [] 2 n)
in
let limit = truncate(sqrt(float n)) in
fold_iter (fun li i ->
if List.mem i li (* test if (i) is prime *)
then (fold_step remove li (i*i) n i)
else li)
li 2 (pred limit)
(* val primes : int -> int list = <fun>*)
;;
</lang>
val primes : int -> int list = <fun>
in the top-level:
 
<lang ocaml># primes 200 ;;
- : int list =
[2; 3; 5; 7; 11; 13; 17; 19; 23; 29; 31; 37; 41; 43; 47; 53; 59; 61; 67; 71;
Line 11,906:
This uses zero to denote struck-out numbers. It is slightly inefficient as it strikes-out multiples above p rather than p<sup>2</sup>
 
<lang ocaml># let rec strike_nth k n l = match l with
| [] -> []
| h :: t ->
if k = 0 then 0 :: strike_nth (n-1) n t
else h :: strike_nth (k-1) n t;;
(* val strike_nth : int -> int -> int list -> int list = <fun>*)
 
# let primes n =
let limit = truncate(sqrt(float n)) in
let rec range a b = if a > b then [] else a :: range (a+1) b in
Line 11,921:
| h :: t -> if h > limit then List.filter ((<) 0) l else
h :: sieve_primes (strike_nth (h-1) h t) in
sieve_primes (range 2 n) ;;
(* val primes : int -> int list = <fun>*)
 
</lang>
# primes 200;;
in the top-level:
<lang ocaml># primes 200;;
- : int list =
[2; 3; 5; 7; 11; 13; 17; 19; 23; 29; 31; 37; 41; 43; 47; 53; 59; 61; 67; 71;
13

edits