题目:
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.
经典解法,从2开始,把2的倍数全部标记完,再标记3的倍数,依次类推,剩下的就是素数。
public class Solution {
public int countPrimes(int n) {
int[] ints = new int[n];
for (int i = 2; i * i < n; i++) {
if (ints[i] == 0) {
for (int j = i; j * i < n; j++)
ints[i * j] = 1;
}
}
int ret = 0;
for (int i = 2; i < n; i++)
if (ints[i] == 0)
ret++;
return ret;
}
}