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

 

 posted on 2015-04-30 15:53  zhuli19901106  阅读(181)  评论(0编辑  收藏  举报