当前位置:网站首页>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月结束了贪心算法的题,开启“巧解数学问题”类的题目
边栏推荐
猜你喜欢

数据湖:流计算处理框架Flink概述

How Navicat Connects to MySQL

07-传统的生产者消费者问题、防止虚假唤醒

MySQL multi-table association one-to-many query to get the latest data

系统(层次)聚类

mysql 8.0.28版本安装配置方法图文教程

数学建模笔记:TOPSIS方法(优劣解距离法)和熵权法修正
选择黑盒测试用例设计方法的综合策略方案总结
[email protected](using passwordYES)"/>Navicat报错:1045-Access denied for user [email protected](using passwordYES)

MySql copies data from one table to another table
随机推荐
【C语言】LeetCode26.删除有序数组中的重复项&&LeetCode88.合并两个有序数组
从DES走到AES(现代密码的传奇之路)
在 .NET MAUI 中如何更好地自定义控件
Introduction and use of apifox (1).
navicat无法连接mysql超详细处理方法
prisma使用mongodb副本集群报错引发的一些列问题
Navicat new database
MYSQL 唯一约束
去字节跳动自动化测试二面原题(根据录音整理)真实有效 26
Go语言中定时任务库Cron使用详解
swinIR论文阅读笔记
AMQP协议详解
高防服务器防御的原理是什么
Google 安装印象笔记剪藏插件
leetcode 665. Non-decreasing Array 非递减数列(中等)
navicat新建数据库
MySQL安装常见报错处理大全
Google notes cut hidden plug-in installation impression
Detailed explanation of AMQP protocol
el-input can only input integers (including positive numbers, negative numbers, 0) or only integers (including positive numbers, negative numbers, 0) and decimals