当前位置:网站首页>力扣 204. 计数质数
力扣 204. 计数质数
2022-07-03 01:02:00 【冷酷的摸鱼小将】
题目
给定整数 n ,返回 所有小于非负整数 n 的质数的数量 。
示例
输入:n = 10
输出:4
解释:小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
输入:n = 0
输出:0
输入:n = 1
输出:0
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/count-primes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:埃氏筛

Java实现
class Solution {
public int countPrimes(int n) {
int[] isPrime = new int[n];
Arrays.fill(isPrime, 1);
int ans = 0;
for (int i = 2; i < n; i++) {
if (isPrime[i] == 1) {
ans++;
if ((long) i * i < n) {
for (int j = i * i; j < n; j += i) {
isPrime[j] = 0;
}
}
}
}
return ans;
}
}

边栏推荐
猜你喜欢

Cut point of undirected graph
![[C language] branch and loop statements (Part 1)](/img/47/6efcc59bd26e26f66c698635c26c8b.png)
[C language] branch and loop statements (Part 1)
![[C language] detailed explanation of pointer and array written test questions](/img/24/c2c372b5c435cbd6eb83ac34b68034.png)
[C language] detailed explanation of pointer and array written test questions
![[fh-gfsk] fh-gfsk signal analysis and blind demodulation research](/img/8a/8ca80f51a03341c982d52980c54b01.png)
[fh-gfsk] fh-gfsk signal analysis and blind demodulation research

Soft exam information system project manager_ Real topic over the years_ Wrong question set in the second half of 2019_ Morning comprehensive knowledge question - Senior Information System Project Man

强化学习 Q-learning 实例详解

leetcode:701. 二叉搜索树中的插入操作【bst的插入】

Find a benchmark comrade in arms | a million level real-time data platform, which can be used for free for life

Leetcode 2097 - Legal rearrangement of pairs

【FPGA教程案例6】基于vivado核的双口RAM设计与实现
随机推荐
The industrial scope of industrial Internet is large enough. The era of consumer Internet is only a limited existence in the Internet industry
每日一题之干草堆的移动
12_ Implementation of rolling automatic video playback effect of wechat video number of wechat applet
18_ The wechat video number of wechat applet scrolls and automatically plays the video effect to achieve 2.0
Kivy教程大全之 创建您的第一个kivy程序 hello word(教程含源码)
Arduino DY-SV17F自动语音播报
Embrace the safety concept of platform delivery
对非ts/js文件模块进行类型扩充
Tp6 fast installation uses mongodb to add, delete, modify and check
[flutter] icons component (fluttericon Download Icon | customize SVG icon to generate TTF font file | use the downloaded TTF icon file)
Esp32 simple speed message test of ros2 (limit frequency)
测试右移:线上质量监控 ELK 实战
Every k nodes in the linked list are flipped
产业互联网的产业范畴足够大 消费互联网时代仅是一个局限在互联网行业的存在
leetcode:871. 最低加油次数【以前pat做过 + 最大堆 +贪心】
Specified interval inversion in the linked list
How wide does the dual inline for bread board need?
MySQL - database query - basic query
kivy教程之在 Kivy App 中使用 matplotlib 的示例
[Arduino experiment 17 L298N motor drive module]