Count Primes Total Accepted: 831 Total Submissions: 6167

来源:互联网 发布:淘宝促销在哪里设置 编辑:程序博客网 时间:2024/06/05 07:44

题目来自:Leetcode


https://leetcode.com/problems/count-primes/

Count Primes

 Total Accepted: 831 Total Submissions: 6167My Submissions

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.

click to show more hints.

References:

How Many Primes Are There?

Sieve of Eratosthenes

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Show Tags
Have you met this question in a real interview? 
Yes
 
No

Discuss

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();    }};


0 0
原创粉丝点击