当前位置:网站首页>【刷题篇】计算质数
【刷题篇】计算质数
2022-07-30 18:50:00 【m0_60631323】
一、题目
OJ链接
给定整数 n ,返回 所有小于非负整数 n 的质数的数量 .
二、题解
思路:将1~n-1上不是素数的数全部除去,剩下的数的数量就是素数
- 除了2,所有的偶数都不是素数,因为4=2x2;6=2x3;8=2x4…
- 在去除掉因子中含有3的所有不是素数的数,
3x2不用再算了,因为计算2x3的时候算过了,所以对于数字i只需从 i x i 开始,3x3=9(不是素数), 3x4不用算(偶数),3x5=15(不是素数)…
public int countPrimes1(int n) {
if(n<3){
return 0;
}
boolean[] f=new boolean[n];
int count =n/2;
for(int i=3;i*i<n;i+=2){
if(f[i]){
//例如i=9时,9在3*3的时候就判断过9不是素数,就已经
//将f[9]=true,而之所以可以跳过9是因为,9*9=3*3*9,
//9*11=3*3*11,就说明,含有9这个因子且不是素数的数,在
//去除以3作为因子所有不是素数的数的时候已经算过了
continue;
}
for(int j=i*i;j<n;j+=2*i){
if(!f[j]){
count--;
f[j]=true;
}
}
}
return count;
}
边栏推荐
- requet.getHeader(“token“) 为null
- 中集世联达飞瞳全球工业人工智能AI领军者,全球顶尖AI核心技术高泛化性高鲁棒性稀疏样本持续学习,工业级高性能成熟AI产品规模应用
- MySQL数据类型
- Chapter 4 Controlling the Execution Flow
- 防抖和节流有什么区别,分别用于什么场景?
- 2种手绘风格效果比较,你更喜欢哪一种呢?
- 终端分屏工具Terminalx的使用
- Codeblocks + Widgets 创建窗口代码分析
- 【Prometheus】Prometheus联邦的一次优化记录[续]
- Recommendation | People who are kind to you, don't repay them by inviting them to eat
猜你喜欢

沉浸式体验科大讯飞2022消博会“官方指定产品”
![[Summary] 1396- 60+ VSCode plugins to create a useful editor](/img/e4/65e55d0e4948c011585b72733d4d19.jpg)
[Summary] 1396- 60+ VSCode plugins to create a useful editor

core sound driver详解

AI Basics: Graphical Transformer

SwiftUI iOS Boutique Open Source Project Complete Baked Food Recipe App based on SQLite (tutorial including source code)

A senior with 13 years of experience in software testing, summed up 5 test employment suggestions....

智慧中控屏

【Pointing to Offer】Pointing to Offer 18. Delete the node of the linked list

网络基础(二)-Web服务器-简介——WampServer集成服务器软件之Apache+MySQL软件安装流程 & netstat -an之检测计算机的端口是否占用

一文读懂“语言模型”
随机推荐
What kind of framework is friendly to developers?
vxe-table实现复选框鼠标拖动选中
荐号 | 对你有恩的人,不要请吃饭来报答
kotlin by lazy
[OC study notes] attribute keyword
(2022杭电多校四)1001-Link with Bracket Sequence II(区间动态规划)
终端分屏工具Terminalx的使用
【网站放大镜效果】两种方式实现
延时队列优化 (2)
Delay queue optimization (2)
Recommended Books | Recommend 3 database books with rave reviews
CIMC Shilian Dafeitong is the global industrial artificial intelligence AI leader, the world's top AI core technology, high generalization, high robustness, sparse sample continuous learning, industri
Swiper rotates pictures and plays background music
2种手绘风格效果比较,你更喜欢哪一种呢?
CCNA-网络汇总 超网(CIDR) 路由最长掩码匹配
Graphic LeetCode -- 11. Containers of most water (difficulty: medium)
Meta元宇宙部门第二季度亏损28亿!仍要继续押注?元宇宙发展尚未看到出路!
《自然语言处理实战入门》---- 文本样本扩展小技巧:使用回译技术进行样本增强
深化校企合作 搭建技术技能人才成长“立交桥”
[TypeScript]编译配置