【刷题-LeetCode】204. Count Primes
2024-10-17 00:38:15
- 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;
}
};
最新文章
- 3dmax导出到blend或者vs中
- 今天第一节PS课
- 如何在CentOS 5/6上安装EPEL 源
- 让vc2010的项目在vc2012也能直接使用,而不必修改PlatformToolSet
- apache 配置多个虚拟主机,不同的端口
- 用shell脚本批量修改文件后缀名
- 滚动光效shader
- HDOJ并查集题目 HDOJ 1213 HDOJ 1242
- [转]mysql-5.6.17-win32免安装版配置
- Solr4.8.0源码分析(27)之ImplicitDocRouter和CompositeIdRouter
- 基于TypeScript的FineUIMvc组件式开发(开头篇)
- return的新思考
- Java进阶(四十一)多线程讲解
- myeclipse中配置自己安装的Tomcat
- [工作积累] shadow map问题汇总
- day-04(jquery)
- SpringBoot项目启用本地Tomcat
- Docker的概述
- redis下操作列表list
- 不能添加重复的Contact到RecipientBox中
热门文章
- 常用DBhelper封装方法
- VC Mirror Driver显示虚拟驱动经典开发
- 使用.NET 6开发TodoList应用(6)——使用MediatR实现POST请求
- 页面调用百度地图但是使用了https证书之后不显示
- c++内存分布之虚函数(单一继承)
- 【LeetCode】1436. 旅行终点站 Destination City (Python)
- 【LeetCode】999. Available Captures for Rook 解题报告(C++)
- 【LeetCode】443. String Compression 解题报告(Python)
- 1067 - Combinations
- CS5211替代LT7211 DP转LVDS芯片方案 替代龙迅LT7211方案