Created
April 3, 2022 20:34
-
-
Save tikipatel/f466536c1a681cd9c7581cad86d22b66 to your computer and use it in GitHub Desktop.
Gets primes by Sieve of Eratosthenes
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 findPrimes(upTo limit: Int) -> [Int] { | |
guard limit > 1 else { return [] } | |
var sieve = Array(repeating: true, count: limit + 1) | |
sieve[0] = false | |
sieve[1] = false | |
for i in 2...limit where sieve[i] { | |
for j in stride(from: i*i, through: limit, by: i) { | |
print(i, j) | |
sieve[j] = false | |
} | |
} | |
return sieve.enumerated().compactMap { $1 == true ? $0 : nil } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment