Created
May 10, 2021 19:18
-
-
Save vrat28/70aa8ff4268396aa418cdb5f90c459c5 to your computer and use it in GitHub Desktop.
Sieve of Erathosthenes (Swift)
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
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