码迷,mamicode.com
首页 > 其他好文 > 详细

204. Count Primes

时间:2016-08-07 12:16:09      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

 1 class Solution {
 2 public:
 3     int countPrimes(int n) {
 4         vector<int> nums(n, 0);
 5         int count = 0;
 6         if (n > 2) ++ count; // 统计2
 7         for (int i = 3; i * i <= n; i += 2) { // 忽略偶数
 8             if (nums[i] == 0) {
 9                 for (int j = i * i; j <= n; j += i) { // j = i * i
10                     nums[j] = 1;
11                 }
12             }
13         }
14         for (int i = 3;  i < nums.size(); i += 2) {
15             if (nums[i] == 0) ++ count;
16         }
17         return count;
18     }
19 };

时间复杂度:O(nloglogn)

除去小地方的trick之外,时间复杂度为技术分享,根据Mertens‘ theorems, 技术分享,M~=0.2614972.

具体证明见论文:http://arxiv.org/pdf/math/0504289.pdf

 

204. Count Primes

标签:

原文地址:http://www.cnblogs.com/shadowwalker9/p/5745755.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!