当前位置:网站首页>leetcode 204. Count Primes 计数质数 (Easy)
leetcode 204. Count Primes 计数质数 (Easy)
2022-08-02 05:03:00 【okokabcd】
一、题目大意
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月结束了贪心算法的题,开启“巧解数学问题”类的题目
边栏推荐
- How much does a test environment cost? Start with cost and efficiency
- ES6——class类实现继承
- 物联网通信协议全解析
- MySql字符串拆分实现split功能(字段分割转列、转行)
- 12个MySQL慢查询的原因分析
- 浏览器的onload事件
- MySQL 8.0.28 version installation and configuration method graphic tutorial
- 2021年软件测试面试题大全
- AMQP协议详解
- The company does not pay attention to software testing, and the new Ali P8 has written a test case writing specification for us
猜你喜欢
CNN 理解神经网络中卷积(大小,通道数,深度)
mysql 存储过程详解
apifox介绍及使用(1)。
【HCIE】NO.30 OSPFv3的基本配置
2021年软件测试面试题大全
Towhee 每周模型
The original question on the two sides of the automatic test of the byte beating (arranged according to the recording) is real and effective 26
【热题】LeetCode 热题 HOT 100分类+题解
本周大新闻|苹果MR已进行Pre-EVT测试,Quest 2涨价100美元
interrupt()、interrupted()和isInterrupted()你真的懂了吗
随机推荐
Mysql 回表
【QT】Qt Creator生成动态库(DLL)并调用
MySQL(7)
MySQL 5.7升级到8.0详细过程
Detailed explanation of AMQP protocol
物联网通信协议全解析
MySQL 8.0.29 解压版安装教程(亲测有效)
MP更新操作方式
【热题】LeetCode 热题 HOT 100分类+题解
matlab simulink 模糊pid结合smith控制温度
Go language study notes - grpc serverclient protobuf Go language from scratch
浏览器的onload事件
牛客-TOP101-BM41
How Navicat Connects to MySQL
腾讯注册中心演进及性能优化实践
2022河南萌新联赛第(四)场:郑州轻工业大学 A - ZZULI
系统(层次)聚类
LeetCode刷题系列 -- 10. 正则表达式匹配
【语义分割】FCN
数据湖:流计算处理框架Flink概述