随笔- 509  文章- 0  评论- 151  阅读- 22万 

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   zhuli19901106  阅读(181)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2014-04-30 Careercup - Facebook面试题 - 5110993575215104
点击右上角即可分享
微信分享提示