Description:
Count the number of prime numbers less than a non-negative number, n.
题意:给出一个数n,求小于n的素数的个数
代码如下:
class Solution
{
public int countPrimes(int n)
{
boolean[] isPrime = new boolean[n];
for (int i = 2; i < n; i++)
{
isPrime[i] = true;
}
int m = (int)Math.sqrt(n);
for (int i = 2; i <= m; i++)
{
if (!isPrime[i]) continue;
for (int j = i * i; j < n; j += i)
{
isPrime[j] = false;
}
}
int count = 0;
for (int i = 2; i < n; i++)
{
if (isPrime[i]) count++;
}
return count;
}
}