标签:
Description:
Count the number of prime numbers less than a non-negative number, n
Hint: The number n could be in the order of 100,000 to 5,000,000.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
厄拉多塞筛法。从第一个素数开始把它的倍数去掉,那么下一个没有被去掉的数一定是素数,重复上面的过程。具体可以看下图。
但是提交却发现超时了!超时了!!!!难道这不是正解?所以经过一顿优化,终于AC掉了。
1 class Solution { 2 public: 3 int countPrimes(int n) { 4 vector<bool> p(n, true); 5 //去掉2以外的所有偶数 6 for (int i = 4; i < n; i += 2) p[i] = false; 7 //上一步已经去掉了偶数,所以这里可以使用i += 2,j += 2 8 for (int i = 3; i * i < n; i += 2) { 9 if (p[i]) for (int j = 3; i * j < n; j += 2) { 10 p[i * j] = false; 11 } 12 } 13 int cnt = 0; 14 for (int i = 2; i < n; ++i) if (p[i]) ++cnt; 15 return cnt; 16 } 17 };
可是,居然花了890ms,可能是用了vector吧,后来又用数组试了一遍,果然:
1 class Solution { 2 public: 3 int countPrimes(int n) { 4 bool *p = new bool[n]; 5 memset(p, true, sizeof(bool) * n); 6 for (int i = 2; i * i < n; ++i) { 7 if (p[i]) for (int j = 2; i * j < n; ++j) { 8 p[i * j] = false; 9 } 10 } 11 int cnt = 0; 12 for (int i = 2; i < n; ++i) if (p[i]) ++cnt; 13 delete [] p; 14 return cnt; 15 } 16 };
没有任何优化,只花了400ms,优化过的只要170ms。所以,vector与原生数组在效率上的差距,由此题可见一斑。
标签:
原文地址:http://www.cnblogs.com/easonliu/p/4461701.html