Created
August 14, 2015 16:09
-
-
Save sortega/2027c5609d082596275f to your computer and use it in GitHub Desktop.
Sequential Eratosthenes sieve
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
class Sieve(maxNumber: Int) { | |
private val candidates = Array.fill(maxNumber + 1)(true) | |
def run(): Unit = { | |
for (index <- 2 to maxNumber) { | |
if (candidates(index)) { | |
crossOutMultiples(index) | |
} | |
} | |
} | |
private def crossOutMultiples(prime: Int): Unit = { | |
println(s"$prime is prime") | |
val firstMultiple = prime * 2 | |
for (index <- firstMultiple to maxNumber by prime) { | |
candidates(index) = false | |
} | |
} | |
} | |
object Sieve extends App { | |
val start = System.currentTimeMillis() | |
new Sieve(maxNumber = 500000).run() | |
println(s"Spent just ${System.currentTimeMillis() - start} millis") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment