Created
September 4, 2012 15:21
-
-
Save squarepegsys/3622323 to your computer and use it in GitHub Desktop.
My first scala experiment -- The Sieve of Eratosthenes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Whenever I start learning a language, the first program I try | |
to write is an implementation of The Sieve of Eratosthenes. | |
It requires you to work with lists, which I think is | |
very important for any language. | |
This is my first stab of the Sieve in Scala. | |
*/ | |
def sieve(total : Int): List[Int] = { | |
var primes : List[Int] = List() | |
var composites : Set[Int] = Set() | |
for (i <- 2 until total+1) { | |
if (! composites.contains(i)) { | |
primes::=i | |
composites = composites ++ Range(i+i,total+1,i).toSet | |
} | |
} | |
primes.sorted | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
After doing some of the koans in Scala Koans, I fixed it up to be more precise and, perhaps, even faster