## Eratosthenes筛法的F#实现

2008-11-11 12:14  Anders Cui  阅读(1488)  评论(5编辑  收藏

Eratosthenes筛法的C#和F#实现

C# Code - Eratosthenes筛法// 返回不大于n的质数构成的数组public static int[] SieveOfEratosthenes(int n){    if (n < 2) { return new int[0]; }    // Init sieve.    bool[] sieve = new bool[n + 1];    for (int i = 2; i < sieve.Length; i++) { sieve[i] = true; }    // Check it.    int upperBound = Convert.ToInt32(Math.Sqrt(n));    for (int i = 2; i <= Math.Sqrt(n); i++)    {        if (sieve[i])        {            for (int j = i + i; j <= n; j += i)            {                sieve[j] = false;            }        }    }    // Count it.    int count = 0;    for (int i = 2; i < sieve.Length; i++)    {        if (sieve[i])        {            count++;        }    }    // Generate the result.    int[] primes = new int[count];    int index = 0;    for (int i = 2; i < sieve.Length; i++)    {        if (sieve[i])        {            primes[index++] = i;        }    }    return primes;}

F# Code - Eratosthenes筛法#lightopen Systemlet generatePrimes n =     match n with    | _ when n < 2 -> [||]    | _ ->        // Init sieve.        let sieve = [| for i in 0 .. n do yield true |]                let isPrime index = sieve.[index]                // Check it.        let upperBound = Convert.ToInt32(Math.Sqrt((float)n))        for i = 2 to upperBound do            if isPrime i then                for j in [i * 2 .. i .. sieve.Length - 1] do                    sieve.[j] <- false                            let mutable count = 0        for i = 2 to sieve.Length - 1 do            if isPrime i then                 count <- count + 1                        let primes = Array.create count 0        let mutable index = 0        for i = 2 to sieve.Length - 1 do            if isPrime i then                primes.[index] <- i                index <- index + 1                        primeslet getInt() =     Convert.ToInt32(Console.ReadLine())    let main() =    let i = getInt()    let primes = generatePrimes i    Console.WriteLine("find {0} prime(s)", primes.Length)    print_any primes    main()Console.Read()

（要了解本人所写的其它F#随笔请查看 F#系列随笔索引

Sieve of Eratosthenes