Advertisement
Guest User

Untitled

a guest
Nov 13th, 2013
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 2.05 KB | None | 0 0
  1. (* https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes *)
  2.  
  3. let debug = ref true ;;
  4.  
  5. let eratos n =
  6.   (* set the upper bound of numbers to check *)
  7.   let upper = n * n + 1 in
  8.  
  9.   (* populate a list with numbers that we can record primeness of *)
  10.   let primes = Array.create upper true in
  11.   (* walk the numbers between 2 and the upper bound *)
  12.   for this_num = 2 to upper do
  13.       (* next, just iterate through the sieve *)
  14.       (* yes, this will hit the same numbers bunches of times, but
  15.        * this isn't about efficiency... *)
  16.       for iterator = this_num to upper do
  17.         let multiple = ref 0 in
  18.         let it_sqd = iterator * iterator in
  19.         (* let next_nonprime = iterator * iterator + !multiple * iterator in *)
  20.           (* while next_nonprime < upper do *)
  21.           try
  22.             while it_sqd + !multiple * it_sqd < Array.length primes do
  23.  
  24.               if !debug then
  25.                 let this_prime = it_sqd + !multiple * it_sqd in
  26.                 Printf.printf "marking %d non-prime\n" this_prime ;
  27.  
  28.               (* well, all these numbers are certainly not prime! *)
  29.               primes.( it_sqd + !multiple * it_sqd ) <- false ;
  30.               multiple := !multiple + 1 ;
  31.             done
  32.           with
  33.             (* this shouldn't happen, but if it does ... *)
  34.             Invalid_argument a -> Printf.printf "%s: record (%d * %d)\n" a !multiple it_sqd;
  35.       done
  36.   done ;
  37.  
  38.   (* bernard on irc points out that 0 and 1 are not primes here *)
  39.   primes.( 0 ) <- false ;
  40.   primes.( 1 ) <- false ;
  41.  
  42.   (* send off our list to the user *)
  43.   primes ;;
  44.  
  45. let nth_prime n =
  46.   let myprimes = Stack.create () in
  47.   let primestatus = eratos n in
  48.   for index = 0 to Array.length primestatus - 1 do
  49.     try
  50.     if primestatus.( index ) = true then
  51.       if !debug then
  52.         Printf.printf "selecting %d as prime\n" index ;
  53.       Stack.push index myprimes ;
  54.     with
  55.       (* again, this shouldn't happen, but ... *)
  56.       Invalid_argument a -> Printf.printf "nth_prime: %s: %d\n" a index ;
  57.   done ;
  58.   Stack.pop myprimes ;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement