当前位置:网站首页>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月结束了贪心算法的题,开启“巧解数学问题”类的题目
边栏推荐
猜你喜欢
随机推荐
二分法中等 LeetCode6133. 分组的最大数量
WEB 渗透之文件类操作
ARFoundation入门教程U2-AR场景截图截屏
Based on php hotel online reservation management system acquisition (php graduation project)
Spark练习题+答案
AIDL communication
2022-08-01 第五小组 顾祥全 学习笔记 day25-枚举与泛型
【C语言实现】最大公约数的3种求法
还在纠结报表工具的选型么?来看看这个
ModuleNotFoundError: No module named 'yaml'
LeetCode952三部曲之一:解题思路和初级解法(137ms,超39%)
Chapter 12, target recognition of digital image processing
C Expert Programming Chapter 1 C: Through the Fog of Time and Space 1.3 The Standard I/O Library and the C Preprocessor
递归(各经典例题分析)
高等代数_证明_矩阵的行列式为特征值之积, 矩阵的迹为特征值之和
Based on php online examination management system acquisition (php graduation design)
C Expert Programming Chapter 1 C: Through the Fog of Time and Space 1.5 ANSI C Today
Homework 8.1 Orphans and Zombies
Spark cluster construction
Spark shuffle tuning








