質數統計查詢 厄拉多塞篩
阿新 • • 發佈:2022-02-12
204. 計數質數
使用厄拉多塞篩法進行 1 到 64 的質數查詢的過程如下:
宣告一個長度為最大限制數的布林陣列。用布林值來區別篩選出的數和質數。
程式碼如下:
class Solution { public: // //超時 // int countPrimes(int n) { // if(n == 0 || n == 1 || n==2) return 0; // if(iszhishu(n-1)) // { // return countPrimes(n-1)+1; // } // else return countPrimes(n-1);// } // bool iszhishu(int n) // { // if(n==2) return true; // for(int i=2; i<n; i++) // { // if(n%i == 0 ) return false; // } // return true; // } int countPrimes(int n) { int count = 0; //初始預設所有數為質數 vector<bool> signs(n, true); for(int i = 2; i < n; i++) { if (signs[i]) { count++; for (int j = i + i; j < n; j += i) { //排除不是質數的數 signs[j] = false; } } } return count; } };