Last active
April 21, 2020 08:58
-
-
Save amfathi/0368508c9352267530dbb7fd6b3d47a2 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes to get primes below a specific positive integer.
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
/// 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