标签:
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
标签:
原文地址:http://www.cnblogs.com/shadowwalker9/p/5745755.html