当前位置:网站首页>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月结束了贪心算法的题,开启“巧解数学问题”类的题目
边栏推荐
- 第3讲:MySQL数据库中常见的几种表字段数据类型
- Based on php online learning platform management system acquisition (php graduation design)
- 找工作必备!如何让面试官对你刮目相看,建议收藏尝试!!
- HCIP---多生成树协议相关知识点
- FusionGAN:A generative adversarial network for infrared and visible image fusion article study notes
- 虚拟内存与物理内存之间的关系
- 2022 版 MySQL 巅峰教程,收藏好,慢慢看
- Dichotomy Medium LeetCode6133. Maximum Number of Groups
- Pytest: begin to use
- SOM网络2: 代码的实现
猜你喜欢
随机推荐
[@synthesize in Objective-C]
scikit-learn no moudule named six
MySQL related knowledge
WEB 渗透之端口协议
图像融合GANMcC学习笔记
LVS负载均衡群集
游戏元宇宙发展趋势展望分析
365天挑战LeetCode1000题——Day 046 生成每种字符都是奇数个的字符串 + 两数相加 + 有效的括号
Uses of Anacoda
可视化——Superset使用
Shell programming conditional statement
Pytest: begin to use
ImportError: `save_weights` requires h5py.问题解决
回收租凭系统100%开源无加密 商城+回收+租赁
HCIP---Architecture of Enterprise Network
FusionGAN:A generative adversarial network for infrared and visible image fusion article study notes
小程序--分包
Based on php online examination management system acquisition (php graduation design)
File operations of WEB penetration
【力扣】字符串相乘