当前位置:网站首页>求n以内的素数
求n以内的素数
2022-07-31 19:21:00 【斯沃福德】
方法一:基础遍历
用数 i 去除以 2到i-1的每个数,一旦整数则break跳出;
List<Integer> list=new ArrayList<>();
for(int i=2;i<=n;i++){
boolean a=true;
for(int j=2;j<i;j++){
if(i%j==0){
a=false;
break; // 跳出循环
}
}
if(a){
// 假设j能遍历到最后都不被整除
list.add(i);
}
}
或者
这种方法 2会无法进入第二个for,所以将2先添加;
List<Integer> list=new ArrayList<>();
for(int i=2;i<=n;i++){
if(i==2) list.add(i);
for(int j=2;j<i;j++){
if(i%j==0){
break;
}
// 如果j 能遍历到最后都不悲整除
if(j==i-1 && i%j!=0){
list.add(i);
}
}
}
方法二:用sqrt优化
整数的因子一大一小,小的那个因子最大不超过该整数的平方根,
注意 :j < = Math.sqrt(i) , 有等号 !
List<Integer> list=new ArrayList<>();
for(int i=2;i<=n;i++){
boolean a=true;
for(int j=2;j<=Math.sqrt(i);j++){
if(i%j==0){
a=false;
break; // 跳出循环
}
}
if(a){
// 假设j能遍历到最后都不被整除
list.add(i);
}
}
方法三:用list中的素数来充当 j
继续探索,问题转换为判断n能否被[2,sqrt(n)]之间的奇数整除,这些奇数里面的合数是多余的。因为任何一个合数都可以分解为它前面若干个素数的积,若不能被它前面的素数整除,则亦不能被此合数整除。所以整除的范围缩小为[2,sqrt(n)]之间的素数。刚好本题目的目的就是求素数,所以可以将求得的素数放在数组内用来判断。
注意:
- j 索引从 0开始 !
- 此时 j 是索引 !j 不能等于 list.size()
List<Integer> list=new ArrayList<>();
for(int i=2;i<=n;i++){
boolean a=true;
for(int j=2;j<=list.size() && j<=Math.sqrt(i);j++){
if(i%j==0){
a=false;
break;
}
}
if(a){
list.add(i);
}
}
边栏推荐
- 保证接口数据安全的10种方式
- MySQL---sort and pagination
- Returns a zero-length array or empty collection, do not return null
- 使用 Flutter 和 Firebase 制作!计数器应用程序
- Get Douyin Video Details API
- [PIMF] OpenHarmony Thesis Club - Inventory of the open source Hongmeng tripartite library [3]
- 多线程之锁
- 广汽本田安全体验营:“危险”是最好的老师
- 全平台GPU通用AI视频补帧超分教程
- ECCV 2022 华科&ETH提出首个用于伪装实例分割的一阶段Transformer的框架OSFormer!代码已开源!...
猜你喜欢
MySQL - multi-table query
Teach you how to deploy Nestjs projects
leetcode: 6135. The longest ring in the graph [inward base ring tree + longest ring board + timestamp]
Bika LIMS 开源LIMS集—— SENAITE的使用(检测流程)
PCB叠层设计
如何识别假爬虫?
Basics of ResNet: Principles of Residual Blocks
这位985教授火了!当了10年博导,竟无一博士毕业!
Unity 之 音频类型和编码格式介绍
What's wrong with the sql syntax in my sql
随机推荐
京东按关键字搜索商品 API
leetcode 665. Non-decreasing Array
第七章
常用的安全渗透测试工具(渗透测试工具)
MySQL---多表查询
What's wrong with the sql syntax in my sql
【愚公系列】2022年07月 Go教学课程 025-递归函数
有一说一,外包公司到底值不值得去?
Go basic part study notes
Get Douyin Video Details API
淘宝/天猫获得淘口令真实url API
flyway的快速入门教程
【AcWing】The 62nd Weekly Match 【2022.07.30】
Chinese encoding Settings and action methods return values
这位985教授火了!当了10年博导,竟无一博士毕业!
移动web开发02
matplotlib ax bar color Set the color, transparency, label legend of the ax bar
九齐ny3p系列语音芯片替代国产方案KT148A性价比更高420秒长度
MySQL - single function
【AcWing】第 62 场周赛 【2022.07.30】