当前位置:网站首页>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月结束了贪心算法的题,开启“巧解数学问题”类的题目
边栏推荐
- Port protocol for WEB penetration
- 基于php动漫周边商城管理系统(php毕业设计)
- 【ASM】字节码操作 MethodWriter
- Chapter 12, target recognition of digital image processing
- Shell programming conditional statement
- The Microsoft campus ambassador to shout you to autumn recruit!
- 游戏元宇宙发展趋势展望分析
- 迁移学习——Discriminative Transfer Subspace Learning via Low-Rank and Sparse Representation
- Appendix A printf, varargs and stdarg A.3 stdarg.h ANSI version of varargs.h
- WEB 渗透之文件类操作
猜你喜欢

Upload markdown documents to blog garden

19 Lectures on Disassembly of Multi-merchant Mall System Functions - Invoice Management on the Platform

AIDL通信

游戏元宇宙发展趋势展望分析

Based on php Xiangxi tourism website management system acquisition (php graduation design)

HCIP---企业网的架构

FusionGAN:A generative adversarial network for infrared and visible image fusion文章学习笔记

还在纠结报表工具的选型么?来看看这个

宝塔应用使用心得

AI应用第一课:支付宝刷脸登录
随机推荐
【C语言实现】两种计算平均成绩题型,博主精心整理,值得一读
Small program -- subcontracting
高等代数_证明_矩阵的任意特征值的代数重数大于等于其几何重数
Spark练习题+答案
365天挑战LeetCode1000题——Day 046 生成每种字符都是奇数个的字符串 + 两数相加 + 有效的括号
C pitfalls and pitfalls Chapter 8 Suggestions and answers 8.2 Answers
Based on php animation peripheral mall management system (php graduation design)
ARFoundation Getting Started Tutorial U2-AR Scene Screenshot Screenshot
9. SAP ABAP OData 服务如何支持删除(Delete)操作
kubernetes CoreDNS全解析
C语言必杀技3行代码把运行速度提升4倍
微软校园大使喊你来秋招啦!
Pytest: begin to use
如何优雅的性能调优,分享一线大佬性能调优的心路历程
迁移学习——Discriminative Transfer Subspace Learning via Low-Rank and Sparse Representation
一个关于操作数据库的建议—用户密码
游戏元宇宙发展趋势展望分析
HCIP---多生成树协议相关知识点
shell specification and variables
基于php影视资讯网站管理系统获取(php毕业设计)