Description:
Count the number of prime numbers less than a non-negative number, n.
思路: 從前向後掃描,第一次遇到沒標記的應該是沒有因子的質數。然後把後面所有這個質數的倍數都標記了。
public int countPrimes(int n) {
if(n<2) return 0;
boolean[] marked = new boolean[n];
int count=0;
for(int i=2; i<n; i++){
//剪枝1:標記所有質數的倍數爲非質數,剩下沒標記的就是質數。
if(!marked[i-1]) {
count++;
//剪枝2:小於當前數的倍數已經考慮過了
int temp = n/i;
for(int j=i; j<=temp; j++){
marked[i*j-1]=true;
}
}
}
return count;
}