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 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
2014-04-30 Careercup - Facebook面试题 - 5110993575215104