2010: The year we make contact RSS 2.0
# Tuesday, February 10, 2009

F# has 'easy button' for finding large primes!  29 lines of code!  Thanks to Chris Smith and his 'completely unique view' on the Sieve of Eratosthenes

#light 

open System.Collections.Generic 
open System 

let findPrimes = 
    seq { 
        yield 2 //2 is a known prime

        let knownComposites = new HashSet<int>() 
        
        //Visit each odd
        for i in 3 .. 2 .. int 1E6 do 
            
            // Check known composites, if not present, it is prime.
            let found = knownComposites.Contains(i) 
            if not found then 
                yield i 

            // Add all multiples of i to our sieve, starting 
            // at i and irecementing by i. 
            do for j in i .. i .. int 1E6 do 
                   knownComposites.Add(j) |> ignore 
    } 
    
printfn "Here are the first 10001 primes:" 
Seq.iter (fun p -> printf "\t%d" p) (Seq.take 10001 findPrimes) 

Console.ReadKey(true)
Tuesday, February 10, 2009 12:15:23 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Bookmark, Tweet, or Share
Stackoverflow.com Rep
Flickr stream
Archive
<February 2009>
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
1234567
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Chris Ballance
Sign In
Statistics
Total Posts: 41
This Year: 6
This Month: 0
This Week: 0
Comments: 9
All Content © 2010, Chris Ballance

Valid XHTML 1.0 Transitional