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的素數(質數)的數目。(《編程之美》上有對應的討論)
西元前250年,希臘數學家厄拉多塞(Eeatosthese)想到了一個非常美妙的質數篩法,減少了逐一檢查每個數的的步驟,可以比較簡單的從一大堆數字之中,篩選出質數來,這方法被稱作厄拉多塞篩法(Sieve of Eeatosthese)。
具體操作:先將 2~n 的各個數放入表中,然後在2的上面畫一個圓圈,然後劃去2的其他倍數;第一個既未畫圈又沒有被劃去的數是3,將它畫圈,再劃去3的其他倍數;現在既未畫圈又沒有被劃去的第一個數 是5,將它畫圈,並劃去5的其他倍數……依次類推,一直到所有小於或等於 n 的各數都畫了圈或劃去爲止。這時,表中畫了圈的以及未劃去的那些數正好就是小於 n 的素數。
其實,當你要畫圈的素數的平方大於 n 時,那麼後面沒有劃去的數都是素數,就不用繼續判了。如下圖:
java代碼如下:
class Solution {
public int countPrimes(int n) {
boolean[]flag=new boolean[n];
if(n<=2)
return 0;
flag[0]=true;
flag[1]=true;
int count=0;
for(int i=2;i<n;i++){
if(!flag[i]){
count++;
for(int j=2;i*j<n;j++){
flag[i*j]=true;
}
}
}
return count;
}
}