Skip to content

Instantly share code, notes, and snippets.

@juliantejera
Created August 10, 2016 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juliantejera/4495f922afada609970539dd54c8b4e0 to your computer and use it in GitHub Desktop.
Save juliantejera/4495f922afada609970539dd54c8b4e0 to your computer and use it in GitHub Desktop.
Sieve of Erastosthene
func sieveOfErastosthene(max: Int) -> [Bool] {
// we assume every number is prime
var flags = Array(count: max + 1, repeatedValue: true)
flags[0] = false
flags[1] = false
let squareRoot = Int(sqrt(Double(max)))
for i in 2...squareRoot {
if flags[i] {
crossOfMultiples(max, prime: i, flags: &flags)
}
}
return flags
}
func crossOfMultiples(max: Int, prime: Int, inout flags: [Bool]) {
for i in (prime * prime).stride(to: max, by: prime) {
flags[i] = false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment