Skip to content

Instantly share code, notes, and snippets.

@vrat28
Last active 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/965d9f918785cc90aad7335668bc0a20 to your computer and use it in GitHub Desktop.
Save vrat28/965d9f918785cc90aad7335668bc0a20 to your computer and use it in GitHub Desktop.
Sieve of Erathostenes
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