Skip to content

Instantly share code, notes, and snippets.

@squarepegsys
Created September 4, 2012 15:21
Show Gist options
  • Save squarepegsys/3622323 to your computer and use it in GitHub Desktop.
Save squarepegsys/3622323 to your computer and use it in GitHub Desktop.
My first scala experiment -- The Sieve of Eratosthenes
/*
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
}
@squarepegsys
Copy link
Author

After doing some of the koans in Scala Koans, I fixed it up to be more precise and, perhaps, even faster

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment