Last active
May 10, 2021 19:18
-
-
Save vrat28/965d9f918785cc90aad7335668bc0a20 to your computer and use it in GitHub Desktop.
Sieve of Erathostenes
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 { | |
public int countPrimes(int n) { | |
if (n < 2) return 0; | |
boolean[] nonPrime = new boolean[n]; | |
nonPrime[1] = true; | |
int numNonPrimes = 1; | |
for (int i=2; i < n; i++) { // O(n) | |
if (nonPrime[i]) continue; | |
int j = i * 2; | |
while (j < n) { // O(log(log(n))) | |
if (!nonPrime[j]) { | |
nonPrime[j] = true; | |
numNonPrimes++; | |
} | |
j += i; | |
} | |
} | |
return (n-1) - numNonPrimes; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment