Advertisement
xavierm02

eratosthene

Nov 7th, 2012
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 0.81 KB | None | 0 0
  1. let rec eratosthene n =
  2.     if n < 2 then
  3.         [ ]
  4.     else
  5.         let primes = eratosthene ( n - 1 ) in
  6.         let rec is_prime primes n =
  7.             match primes with
  8.                 | [ ] -> true
  9.                 | head :: tail -> n mod head <> 0 && is_prime tail n
  10.         in
  11.         if is_prime primes n then
  12.             primes @ [ n ] (* I don't know if I should reverse the list or not... because appending would be faster but 2 divides more numbers than 3 etc. so it would take longer to find out a number isn't a prime... *)
  13.         else
  14.             primes
  15. ;;
  16.  
  17. let rec print_list l =
  18.     match l with
  19.         | [ ] -> ( )
  20.         | head :: tail -> begin
  21.             print_int head;
  22.             print_newline ( );
  23.             print_list tail
  24.         end
  25. ;;
  26.  
  27. print_list ( eratosthene 100 );;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement