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

Count Primes Total Accepted: 831 Total Submissions: 6167

时间:2015-04-27 23:50:05      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

题目来自: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.

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


Count Primes Total Accepted: 831 Total Submissions: 6167

标签:

原文地址:http://blog.csdn.net/zhouyelihua/article/details/45317789

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