Created
August 10, 2016 22:03
-
-
Save juliantejera/4495f922afada609970539dd54c8b4e0 to your computer and use it in GitHub Desktop.
Sieve of Erastosthene
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
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