Skip to content

Instantly share code, notes, and snippets.

@vrat28
Created May 10, 2021 19:18
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 vrat28/70aa8ff4268396aa418cdb5f90c459c5 to your computer and use it in GitHub Desktop.
Save vrat28/70aa8ff4268396aa418cdb5f90c459c5 to your computer and use it in GitHub Desktop.
Sieve of Erathosthenes (Swift)
class Solution {
func countPrimes(_ n: Int) -> Int {
if n < 2 { return 0}
var nonPrimes = [Bool](repeating:false,count: n)
nonPrimes[1] = true
var numNonPrimes = 1
for i in 2..<n {
if nonPrimes[i] == true{
continue
}
var j = 2 * i
while j < n {
if nonPrimes[j] == false {
nonPrimes[j] = true
numNonPrimes += 1
}
j += i
}
}
return n - 1 - numNonPrimes
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment