標籤:
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,統計出比n小的質數的個數。此題乍一看很簡單,就是寫一個函數判斷是否為質數,再進行n次迴圈即可。但測試資料會出現非常大的n,用一般方法會運行逾時。傳統方法判斷一個數是否為質數的時間複雜度為O(log2n)(與根號n作比較),n個數的時間複雜度再乘以n。
leetcode將此題標為簡單,因為他給了一系列提示,給出了另外一種演算法,用更多的記憶體換取時間上的縮短。整體思路是產生一個元素個數為n(n為輸入)的數組(初始化為0),把從4開始到n結束所有的合數設定為1,再從2遍曆數組,遇到為0的元素計數加一即可。我先把代碼粘在下面,看不懂可以看leetcode的題目連結https://leetcode.com/problems/count-primes/ 上面有完整的hints
1 class Solution { 2 public: 3 void SetFlag(vector<int>& vec, int n, int max) { 4 long long int t = n; //轉換成長長整形,否則n平方後可能會溢出 5 for(long long int i = t * t; i < max; i += n) { 6 vec[i] = 1; 7 } 8 } 9 int countPrimes(int n) {10 if(n < 3) return 0;11 // int *vec = (int *)malloc(sizeof(int) * n);12 vector<int> vec(n + 1, 0);13 for(int i = 2; i < n; i++) {14 SetFlag(vec, i, n);15 }16 int count = 0;17 for(int j = 2; j < n; j++) {18 if(!vec[j]) {19 count++;20 }21 }22 return count;23 }24 };View Code
204 Count Primes