The sieve of eratosthenes

OCaml

(* Sieve of Eratosthenes in OCaml
 * Written by Rob Hoelz
 *)

open Arg
open List

let rec genList start stop =
    if start = stop then
        [start]
    else
        start :: (genList (start + 1) stop)

class sieve lim =
    let pri = genList 2 lim in
    object
        val mutable primes = pri
        val limit = lim
        method generate =
            let rec gen' = function
                | [] -> []
                | (h::t) ->
                    if (h * h) <= limit then
                        h :: gen' (filter (fun x -> (x mod h) <> 0) t)
                    else
                        (h::t) in
            primes <- gen' primes
        method print_primes =
            let rec print_primes' = function
                | [] -> ()
                | (h::t) -> print_int h; print_string " "; print_primes' t in
            print_primes' primes;
            print_newline ();
    end

let main =
    let argref = (ref "") in
    parse [] (fun y -> argref := y) "Syntax error";
    let s = new sieve (int_of_string !argref) in
    s#generate;
    s#print_primes;;

let _ = main

back to Eratosthenes page

stats

It is Sunday October 12, 2008 1:37 pm
This page served 881 times
This page last modified: April 14, 2008 11:28 am
Your IP address is: 38.103.63.61
You are browsing using: CCBot/1.0 (+http://www.commoncrawl.org/bot.html)
You are browsing from: United States.
badcomputer.org's uptime: 13:37:47 up 74 days, 04:44, 1 user, load average: 0.00, 0.00, 0.00

local

home | unix stuff | dir2ogg | sneetchalizer | wmainfo | q&d guide to permissions | q&d guide to tar and gzip | code | MS rant | browser shootout | linux & iAudio X5 | photos | music | programming poetry | sieve of Eratosthenes | plea | rain | suffer | archive | about | recipes | compaqr3000 | sitemap

search

Google

credits

hacker emblem

This page, and all pages on this site were created and are maintained by Darren Kirby using valid XHTML 1.0 and CSS, and are ©copyright 2002 - 2008. The Penguin image was created by Tukka, and is used by permission. Inspiration for the look of this site was provided by Eric A. Meyer's CSS gallery. This website runs on Gentoo Linux. It is served by Apache. PHP and MySQL hold together the backend.

advertisement