How to Find Prime Number Efficiently
// Returns several primes in the interval [2, n)
int countPrimes(int n)
// E.g. countPrimes (10) returns 4
// Because 2,3,5,7 is prime numbersint countPrimes(int n) {
int count = 0;
for (int i = 2; i < n; i++)
if (isPrim(i)) count++;
return count;
}
// Determines whether integer n is prime
boolean isPrime(int n) {
for (int i = 2; i < n; i++)
if (n % i == 0)
// There are other divisibility factors
return false;
return true;
}Efficient implementation countPrimes
countPrimesLast updated