Skip to content

Instantly share code, notes, and snippets.

@tikipatel
Created April 3, 2022 20:34
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 tikipatel/f466536c1a681cd9c7581cad86d22b66 to your computer and use it in GitHub Desktop.
Save tikipatel/f466536c1a681cd9c7581cad86d22b66 to your computer and use it in GitHub Desktop.
Gets primes by Sieve of Eratosthenes
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