1. Count Primes

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

Example:

Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

解法1 埃氏筛法

class Solution {
public:
int countPrimes(int n) {
if(n < 2)return 0;
vector<bool>isPrime(n, true);
isPrime[0] = false;
isPrime[1] = false;
int ans = 0;
for(int i = 2; i < n; ++i){
if(isPrime[i]){
ans++;
int k = 2;
while(k * i < n){
isPrime[k*i] = false;
k++;
}
}
}
return ans;
}
};

解法2 欧拉筛法(线性筛)

class Solution {
public:
int countPrimes(int n) {
if(n < 3)return 0;
vector<bool>isPrime(n, true);
vector<int>Prime(n);
isPrime[0] = false;
isPrime[1] = false;
int cnt = 0;
for(int i = 2; i <= n -1 ; ++i){
if(isPrime[i]){
Prime[cnt++] = i;
}
for(int j = 0; j < cnt && i * Prime[j] < n; ++j){
isPrime[Prime[j]*i] = false;
}
}
return cnt;
}
};

最新文章

  1. 3dmax导出到blend或者vs中
  2. 今天第一节PS课
  3. 如何在CentOS 5/6上安装EPEL 源
  4. 让vc2010的项目在vc2012也能直接使用,而不必修改PlatformToolSet
  5. apache 配置多个虚拟主机,不同的端口
  6. 用shell脚本批量修改文件后缀名
  7. 滚动光效shader
  8. HDOJ并查集题目 HDOJ 1213 HDOJ 1242
  9. [转]mysql-5.6.17-win32免安装版配置
  10. Solr4.8.0源码分析(27)之ImplicitDocRouter和CompositeIdRouter
  11. 基于TypeScript的FineUIMvc组件式开发(开头篇)
  12. return的新思考
  13. Java进阶(四十一)多线程讲解
  14. myeclipse中配置自己安装的Tomcat
  15. [工作积累] shadow map问题汇总
  16. day-04(jquery)
  17. SpringBoot项目启用本地Tomcat
  18. Docker的概述
  19. redis下操作列表list
  20. 不能添加重复的Contact到RecipientBox中

热门文章

  1. 常用DBhelper封装方法
  2. VC Mirror Driver显示虚拟驱动经典开发
  3. 使用.NET 6开发TodoList应用(6)——使用MediatR实现POST请求
  4. 页面调用百度地图但是使用了https证书之后不显示
  5. c++内存分布之虚函数(单一继承)
  6. 【LeetCode】1436. 旅行终点站 Destination City (Python)
  7. 【LeetCode】999. Available Captures for Rook 解题报告(C++)
  8. 【LeetCode】443. String Compression 解题报告(Python)
  9. 1067 - Combinations
  10. CS5211替代LT7211 DP转LVDS芯片方案 替代龙迅LT7211方案