当前位置:网站首页>力扣 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;
}
}

边栏推荐
- 看完这篇 教你玩转渗透测试靶机Vulnhub——DriftingBlues-9
- [FPGA tutorial case 6] design and implementation of dual port RAM based on vivado core
- [androd] module dependency replacement of gradle's usage skills
- Appuyez sur l'apprentissage de l'esprit de frappe - reconnaissance des coordonnées de fond multithreadées
- MySQL foundation 07-dcl
- Basic concept and implementation of overcoming hash
- Button wizard play strange learning - go back to the city to buy medicine and add blood
- 不登陆或者登录解决oracle数据库账号被锁定。
- MySQL foundation 06 DDL
- tp6快速安装使用MongoDB实现增删改查
猜你喜欢

FPGA - 7 Series FPGA internal structure clocking -04- multi area clock

Leetcode 2097 - Legal rearrangement of pairs

leetcode:871. 最低加油次数【以前pat做过 + 最大堆 +贪心】

leetcode 2097 — 合法重新排列数对

MySQL基础用法02

【FH-GFSK】FH-GFSK信号分析与盲解调研究

看完这篇 教你玩转渗透测试靶机Vulnhub——DriftingBlues-9

寻找标杆战友 | 百万级实时数据平台,终身免费使用

Excel removes the data after the decimal point and rounds the number

matlab 多普勒效应产生振动信号和处理
随机推荐
Niu Ke swipes questions and clocks in
Is there anything in common between spot gold and spot silver
Basic concept and implementation of overcoming hash
leetcode 6103 — 从树中删除边的最小分数
关于Fibonacci数列
excel去除小数点后面的数据,将数字取整
MySQL foundation 04 MySQL architecture
看完这篇 教你玩转渗透测试靶机Vulnhub——DriftingBlues-9
Usage of using clause in kingbases alter table
Makefile中wildcard、patsubst、notdir的含义
Key wizard hit strange learning - automatic path finding back to hit strange points
不登陆或者登录解决oracle数据库账号被锁定。
excel IF公式判断两列是否相同
删除有序链表中重复的元素-II
产业互联网的产业范畴足够大 消费互联网时代仅是一个局限在互联网行业的存在
d. LDC build shared library
Cut point of undirected graph
leetcode:701. Insertion in binary search tree [BST insertion]
Inversion de l'intervalle spécifié dans la liste des liens
强化学习 Q-learning 实例详解