当前位置:网站首页>find prime numbers up to n
find prime numbers up to n
2022-07-31 19:28:00 【swofford】
方法一:基础遍历
用数 i 去除以 2到i-1的每个数,Once the integer isbreak跳出;
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){
// 假设jIt can traverse to the end without being divisible
list.add(i);
}
}
或者
这种方法 2will not be able to enter the second onefor,所以将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 It can be traversed to the end without being divisible
if(j==i-1 && i%j!=0){
list.add(i);
}
}
}
方法二:用sqrt优化
The factors of integers are large and small,The smaller factor does not exceed the integer平方根,
注意 :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){
// 假设jIt can traverse to the end without being divisible
list.add(i);
}
}
方法三:用listThe prime numbers in j
继续探索,Questions turn into judgmentsn能否被[2,sqrt(n)]odd integer division between,The composite numbers within these odd numbers are redundant.Because any composite number can be decomposed into the product of several prime numbers in front of it,If it is not divisible by the prime number preceding it,is also not divisible by this composite number.So the divisible range is reduced to [2,sqrt(n)]之间的素数.The purpose of this question is to find prime numbers,Therefore, the obtained prime numbers can be placed in the array for judgment.
注意:
- 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);
}
}
边栏推荐
- Socket回顾与I/0模型
- Tkinter 入门之旅
- mysql的备份表的几种方法
- 财务盈利、偿债能力指标
- 迁移学习——Domain Adaptation
- 2022 Android interview summary (with interview questions | source code | interview materials)
- Get Douyin Video Details API
- 求n以内的素数
- How programmers learn open source projects, this article tells you
- matplotlib ax bar color 设置ax bar的颜色、 透明度、label legend
猜你喜欢
随机推荐
MySQL---子查询
Batch (batch size, full batch, mini batch, online learning), iterations and epochs in deep learning
leetcode 665. Non-decreasing Array
ResNet的基础:残差块的原理
程序员如何学习开源项目,这篇文章告诉你
Taobao/Tmall get Taobao password real url API
求n以内的素数
The server encountered an internal error that prevented it from fulfilling this request的一种解决办法[通俗易懂]
迁移学习——Domain Adaptation
Redis综述篇:与面试官彻夜长谈Redis缓存、持久化、淘汰机制、哨兵、集群底层原理!...
The article you worked so hard to write may not be your original
Getting Started with Tkinter
MySQL---aggregate function
Get Douyin Video Details API
AI 自动写代码插件 Copilot(副驾驶员)
Mobile web development 02
Teach you how to deploy Nestjs projects
MATLAB程序设计与应用 2.4 MATLAB常用内部函数
有一说一,外包公司到底值不值得去?
Basic Grammar Introduction of Carbon Tutorial (Tutorial)








