Skip to content

Instantly share code, notes, and snippets.

@amfathi
Last active April 21, 2020 08:58
Show Gist options
  • Save amfathi/0368508c9352267530dbb7fd6b3d47a2 to your computer and use it in GitHub Desktop.
Save amfathi/0368508c9352267530dbb7fd6b3d47a2 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes to get primes below a specific positive integer.
/// All the primes number below & including 10e7 using Sieve algorithm O(n log log n).
/// https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
func sieve() -> [Int] {
let limit = 10000000 // 10e7
// Create an array assumping all numbers are primes
var isPrime = Array(repeating: true, count: limit)
// Mark trivial cases as not primes
isPrime[0] = false
isPrime[1] = false
// Looping till the square root of the limit is enough (explaintion is provided in the link above)
let root = Int(sqrt(Double(limit)))
for current in 2...root where isPrime[current] {
// Starting from the square and going up marking them as non-primes (explaing why square is in the link)
var multiple = current * current
while multiple < limit {
isPrime[multiple] = false
multiple += current
}
}
// loop over isPrime array to filter prime numbers
var primes = [Int]()
for (index, isPrime) in isPrime.enumerated() where isPrime {
primes.append(index)
}
return primes
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment