首页 > 其他 > 详细

204. Count Primes

时间:2016-08-13 19:27:37      阅读:241      评论:0      收藏:0      [点我收藏+]

Description:

Count the number of prime numbers less than a non-negative number, n.

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

此方法效率很高。

 1 class Solution {
 2 public:
 3     int countPrimes(int n) {
 4         if(n <= 2)
 5         {
 6             return 0;
 7         }
 8         int count = 1;
 9         bool flag = false;
10         bool hash[n] = {false};
11         for (int i = 3; i < n; i+=2)
12         {
13             if(hash[i]==false)
14             {
15                 ++count;
16             }
17             if(i>sqrt(n)) continue;
18             for(int j = i*i; j < n; j+=i)
19             {
20                 hash[j] = true;
21             }
22         }
23         return count;
24         
25     }
26 };

 

204. Count Primes

原文:http://www.cnblogs.com/hhboboy/p/5768523.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!