当前位置:网站首页>leetcode 204. Count Primes 计数质数 (Easy)
leetcode 204. Count Primes 计数质数 (Easy)
2022-08-01 21:46:00 【InfoQ】
一、题目大意
- 0 <= n <= 5 * 106
二、解题思路
三、解题方法
3.1 Java实现
public class Solution {
public int countPrimes(int n) {
if (n <= 2) {
return 0;
}
boolean[] prime = new boolean[n];
Arrays.fill(prime, true);
int i = 3;
int sqrtn = (int) Math.sqrt(n);
// 偶数一定不是质数
int count = n / 2;
while (i <= sqrtn) {
// 最小质因子一定小于等于开方数
for (int j = i * i; j < n; j += 2 * i) {
// 避免偶数和重复遍历
if (prime[j]) {
count--;
prime[j] = false;
}
}
do {
i+= 2;
// 避免偶数和重复遍历
} while (i <= sqrtn && !prime[i]);
}
return count;
}
}
四、总结小记
- 2022/8/1 7月结束了贪心算法的题,开启“巧解数学问题”类的题目
边栏推荐
- LeetCode952三部曲之二:小幅度优化(137ms -> 122ms,超39% -> 超51%)
- shell编程规范与变量
- [@synthesize in Objective-C]
- Upload markdown documents to blog garden
- Chapter 12, target recognition of digital image processing
- 【C语言实现】整数排序-四种方法,你都会了吗、
- Appendix A printf, varargs and stdarg A.1 printf family of functions
- AI应用第一课:支付宝刷脸登录
- 一个关于操作数据库的建议—用户密码
- 第一讲 测试知多少
猜你喜欢
随机推荐
The difference between groupByKey and reduceBykey
SOM网络2: 代码的实现
Spark shuffle调优
C Expert Programming Chapter 1 C: Through the Fog of Time and Space 1.1 The Prehistoric Phase of the C Language
ModuleNotFoundError: No module named ‘yaml‘
【牛客刷题-SQL大厂面试真题】NO4.出行场景(某滴打车)
shell编程规范与变量
基于php在线学习平台管理系统获取(php毕业设计)
Based on php online examination management system acquisition (php graduation design)
C Expert Programming Chapter 1 C: Through the Fog of Time and Space 1.2 Early Experience of C Language
Spark cluster construction
Spark练习题+答案
Image fusion GANMcC study notes
19 Lectures on Disassembly of Multi-merchant Mall System Functions - Invoice Management on the Platform
kubernetes CoreDNS全解析
【力扣】字符串相乘
2022-08-01 第五小组 顾祥全 学习笔记 day25-枚举与泛型
今日睡眠质量记录74分
Centos7--MySQL的安装
第一讲 测试知多少