Prime Number Related
boolean isPrime(int n) {
if (n <= 1 || n % 2 == 0) {
return false;
}
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
// Sieve of Eratosthenes - https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
// Time Complexity: O(N log (log N))
public int countPrimes(int n) {
boolean[] notPrimes = new boolean[n];
for (int i = 2; i * i < n; ++i) {
if (!notPrimes[i]) {
for (int j = 2; j * i < n; ++j) {
notPrimes[j * i] = true;
}
}
}
int cnt = 0;
for (int i = 2; i < n; ++i) {
cnt += notPrimes[i] ? 0 : 1;
}
return cnt;
}