~ubuntu-branches/ubuntu/hardy/ocaml-doc/hardy

« back to all changes in this revision

Viewing changes to examples/basics/sieve_vect_unsafe.ml

  • Committer: Bazaar Package Importer
  • Author(s): Samuel Mimram
  • Date: 2007-09-08 01:49:22 UTC
  • mfrom: (0.1.3 upstream)
  • Revision ID: james.westby@ubuntu.com-20070908014922-lvihyehz0ndq7suu
Tags: 3.10-1
* New upstream release.
* Removed camlp4 documentation since it is not up-to-date.
* Updated to standards version 3.7.2, no changes needed.
* Updated my email address.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
(***********************************************************************)
2
 
(*                                                                     *)
3
 
(*                           Objective Caml                            *)
4
 
(*                                                                     *)
5
 
(*               Pierre Weis, projet Cristal, INRIA Rocquencourt       *)
6
 
(*                                                                     *)
7
 
(*  Copyright 2001 Institut National de Recherche en Informatique et   *)
8
 
(*  en Automatique.  All rights reserved.  This file is distributed    *)
9
 
(*  only by permission.                                                *)
10
 
(*                                                                     *)
11
 
(***********************************************************************)
12
 
 
13
 
(* Erathostene sieve, imperative version.
14
 
   A vector is initialized with integers.
15
 
   Then the vector is sieved. *)
16
 
 
17
 
let fixed_bound = 5000000;;
18
 
 
19
 
let sieve max =
20
 
 
21
 
 let v = Array.init max (fun i -> i + 1) in
22
 
 for i = 0 to max - 1 do v.(i) <- i + 1 done;
23
 
 
24
 
 let prime_count = ref 0 in
25
 
 
26
 
 v.(0) <- 0;
27
 
 prime_count := 0;
28
 
 
29
 
 for i = 1 to max - 1 do
30
 
  if Array.unsafe_get v i <> 0 then begin
31
 
   prime_count := !prime_count + 1;
32
 
   let prime = i + 1 in
33
 
   let rec sieve j =
34
 
    if j < max then begin Array.unsafe_set v j 0; sieve (j + prime) end in
35
 
   sieve (i + prime)
36
 
  end
37
 
 done;
38
 
 Printf.printf
39
 
  "There are %d primes less than or equal to %d.\n" !prime_count max;;
40
 
 
41
 
let main () =
42
 
 let max =
43
 
   try int_of_string (Sys.argv.(1))
44
 
   with _ -> fixed_bound in
45
 
 sieve max;;
46
 
 
47
 
main ();;