当前位置:网站首页>力扣 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;
}
}
边栏推荐
- [C language] detailed explanation of pointer and array written test questions
- 【FPGA教程案例5】基于vivado核的ROM设计与实现
- Trois tâches principales: asynchrone, courrier et timing
- [day 29] given an integer, please find its factor number
- MySQL --- 数据库查询 - 条件查询
- Is there anything in common between spot gold and spot silver
- 【无标题】
- excel去除小数点后面的数据,将数字取整
- Kivy tutorial - example of using Matplotlib in Kivy app
- Telephone network problems
猜你喜欢
MySQL foundation 05 DML language
JS inheritance and prototype chain
Telephone network problems
Cut point of undirected graph
Androd gradle's substitution of its use module dependency
Database SQL language 02 connection query
Basic remote connection tool xshell
Find a benchmark comrade in arms | a million level real-time data platform, which can be used for free for life
Matlab saves the digital matrix as geospatial data, and the display subscript index must be of positive integer type or logical type. Solve the problem
Trois tâches principales: asynchrone, courrier et timing
随机推荐
SwiftUI 组件大全之使用 SceneKit 和 SwiftUI 构建交互式 3D 饼图(教程含源码)
合并K个已排序的链表
kivy教程之在 Kivy App 中使用 matplotlib 的示例
465. DFS backtracking of optimal bill balance
寻找标杆战友 | 百万级实时数据平台,终身免费使用
对非ts/js文件模块进行类型扩充
Is there anything in common between spot gold and spot silver
Is there a handling charge for spot gold investment
Type expansion of non ts/js file modules
异步、邮件、定时三大任务
有向图的强连通分量
1696C. Fishingprince plays with array [thinking questions + intermediate state + optimized storage]
leetcode:701. 二叉搜索树中的插入操作【bst的插入】
Database SQL language 02 connection query
软考信息系统项目管理师_历年真题_2019下半年错题集_上午综合知识题---软考高级之信息系统项目管理师053
R language uses coin package to apply permutation tests to independence problems (permutation tests, whether response variables are independent of groups, are two numerical variables independent, and
How wide does the dual inline for bread board need?
Arduino DY-SV17F自动语音播报
Assets, vulnerabilities, threats and events of the four elements of safe operation
Specified interval inversion in the linked list