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

LeetCode - Count Primes

时间:2015-04-30 17:29:12      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

Count Primes

2015.4.30 15:51

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

Solution:

  Sieve of Eratosthenes.

Accepted code:

 1 // 2CE, 1MLE, 1RE, 1AC, trial and error
 2 #include <cstring>
 3 using namespace std;
 4 
 5 const int N = 2000000;
 6 int b[N + 1], c[N + 1];
 7 bool once = false;
 8 
 9 class Solution {
10 public:
11     Solution() {
12         Eratosthenes();
13     }
14     
15     int countPrimes(int n) {
16         return n > 0 ? c[n - 1] : 0;
17     }
18 private:
19     void Eratosthenes() {
20         if (once) {
21             return;
22         }
23         
24         int i, j;
25         
26         memset(b, 0, (N + 1) * sizeof(int));
27         memset(c, 0, (N + 1) * sizeof(int));
28         b[0] = b[1] = 1;
29         for (i = 2; i <= N / i; ++i) {
30             if (b[i]) {
31                 continue;
32             }
33             for (j = i; j <= N / i; ++j) {
34                 b[i * j] = 1;
35             }
36         }
37         for (i = 1; i <= N; ++i) {
38             c[i] = b[i] ? c[i - 1] : c[i - 1] + 1;
39         }
40         once = true;
41     }
42 };

 

LeetCode - Count Primes

标签:

原文地址:http://www.cnblogs.com/zhuli19901106/p/4469118.html

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