Description:
Count the number of prime numbers less than a non-negative number, n.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
題目描述:求小於正整數n的所有素數個數。
注意:1不是素數也不是合數,其他正整數要麼是素數,要麼是合數,通常用兩個for循環依次除小於該數的每個數字的方法判斷效率太低,AC不了。不如換個思路:求小於n的所有合數,若某一個數字的平方小於n,那麼這個數是符合條件的合數,而平方再加上若干個該數,也是合數。
public static int countPrimes(int n) {
int res = 0;
boolean[] used = new boolean[n];
for (int i = 2; i <= Math.sqrt(n); i++) {
if (!used[i]) {
int temp = i * i;
while (temp < n) {
used[temp] = true;
temp += i;
}
}
}
for (int i = 2; i < n; i++) {
if (!used[i]) {
res++;
}
}
return res;
}
效率剛剛地。