标签:
题目来自:Leetcode
https://leetcode.com/problems/count-primes/
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.
class Solution { public: int countPrimes(int n) { if(n<=2) return 0; if(n==3) return 1; bitset<5000001> b; b.set(); b.reset(0); b.reset(1); int imax=sqrt(n)+1; int j; for(int i=2;i<=imax;++i) { if(b.test(i)==true) { j=i*i; while(j<n) { b.reset(j); // cout<<"j="<<j<<endl; j+=i; } } } b.flip(); return n-b.count(); } };
Count Primes Total Accepted: 831 Total Submissions: 6167
标签:
原文地址:http://blog.csdn.net/zhouyelihua/article/details/45317789