当前位置:网站首页>leetcode 204. Count Primes 计数质数 (Easy)
leetcode 204. Count Primes 计数质数 (Easy)
2022-08-01 21:46:00 【InfoQ】
一、题目大意
https://leetcode.cn/problems/count-primes
给定整数 n ,返回 所有小于非负整数 n 的质数的数量 。
示例 1:
输入:n = 10输出:4解释:小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
示例 2:
输入:n = 0输出:0
示例 3:
输入:n = 1输出:0
提示:
- 0 <= n <= 5 * 106
二、解题思路
输入一个整数,输出也是一个整数,表示小于输入数的质数的个数。埃拉托斯特尼筛法,是判断一个整数是否是质数的方法。并且它可以在判断一个整数n时,同时判断所小于n的整数,因此非常适合这个问题。其原理是:从1到n遍历,假设当前遍历到m,则把所有小于n的、且是m的倍数的整数标为和数;遍历完成后,没有被标为和数的数字即为质数。
三、解题方法
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月结束了贪心算法的题,开启“巧解数学问题”类的题目
边栏推荐
猜你喜欢
随机推荐
C Pitfalls and Defects Chapter 7 Portability Defects 7.8 Size of Random Numbers
Centos7--MySQL的安装
基于php在线考试管理系统获取(php毕业设计)
Appendix A printf, varargs and stdarg A.3 stdarg.h ANSI version of varargs.h
shell脚本
入门数据库Days4
Appendix A printf, varargs and stdarg a. 2 use varargs. H to realize the variable argument list
图像融合GANMcC学习笔记
AIDL communication
”sed“ shell脚本三剑客
可视化——Superset使用
WEB 渗透之文件类操作
方舟开服需要知道的那些事
C Expert Programming Chapter 1 C: Through the Fog of Time and Space 1.4 K&R C
SAP ABAP OData 服务如何支持删除(Delete)操作试读版
方舟生存进化是什么游戏?好不好玩
【C语言实现】最大公约数的3种求法
【Unity实战100例】文件压缩Zip和ZIP文件的解压
kubernetes CoreDNS全解析
教你VSCode如何快速对齐代码、格式化代码









