204 Count Primes

來源:互聯網
上載者:User

標籤:

 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.