1995-08-09 08:06:35 -07:00
|
|
|
(***********************************************************************)
|
|
|
|
(* *)
|
1996-04-30 07:53:58 -07:00
|
|
|
(* Objective Caml *)
|
1995-08-09 08:06:35 -07:00
|
|
|
(* *)
|
|
|
|
(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
|
|
|
|
(* *)
|
1996-04-30 07:53:58 -07:00
|
|
|
(* Copyright 1996 Institut National de Recherche en Informatique et *)
|
1995-08-09 08:06:35 -07:00
|
|
|
(* Automatique. Distributed only by permission. *)
|
|
|
|
(* *)
|
|
|
|
(***********************************************************************)
|
|
|
|
|
|
|
|
(* $Id$ *)
|
|
|
|
|
1995-05-04 03:15:53 -07:00
|
|
|
(* Eratosthene's sieve *)
|
|
|
|
|
|
|
|
(* interval min max = [min; min+1; ...; max-1; max] *)
|
|
|
|
|
|
|
|
let rec interval min max =
|
|
|
|
if min > max then [] else min :: interval (min + 1) max
|
|
|
|
|
|
|
|
|
|
|
|
(* filter p L returns the list of the elements in list L
|
|
|
|
that satisfy predicate p *)
|
|
|
|
|
|
|
|
let rec filter p = function
|
|
|
|
[] -> []
|
|
|
|
| a::r -> if p a then a :: filter p r else filter p r
|
|
|
|
|
|
|
|
|
|
|
|
(* Application: removing all numbers multiple of n from a list of integers *)
|
|
|
|
|
|
|
|
let remove_multiples_of n =
|
|
|
|
filter (fun m -> m mod n <> 0)
|
|
|
|
|
|
|
|
|
|
|
|
(* The sieve itself *)
|
|
|
|
|
|
|
|
let sieve max =
|
|
|
|
let rec filter_again = function
|
|
|
|
[] -> []
|
|
|
|
| n::r as l ->
|
|
|
|
if n*n > max then l else n :: filter_again (remove_multiples_of n r)
|
|
|
|
in
|
|
|
|
filter_again (interval 2 max)
|
|
|
|
|
|
|
|
|
|
|
|
let rec do_list f = function
|
|
|
|
[] -> ()
|
|
|
|
| a::l -> f a; do_list f l
|
|
|
|
|
|
|
|
|
|
|
|
let _ =
|
|
|
|
do_list (fun n -> print_int n; print_string " ") (sieve 40000);
|
|
|
|
print_newline();
|
|
|
|
exit 0
|