当前位置:网站首页>求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);
}
}
边栏推荐
- mysql的备份表的几种方法
- 【AcWing】第 62 场周赛 【2022.07.30】
- BOW/DOM(上)
- Architect 04 - Application Service Encryption Design and Practice
- rj45对接头千兆(百兆以太网接口定义)
- What's wrong with the sql syntax in my sql
- 深度学习中的batch(batch size,full batch,mini batch, online learning)、iterations与epoch
- The new telecom "routine", my dad was tricked!
- MySQL---sort and pagination
- Arduino框架下STM32全系列开发固件安装指南
猜你喜欢
GateWay实现负载均衡
这位985教授火了!当了10年博导,竟无一博士毕业!
Made with Flutter and Firebase!counter application
GAC Honda Safety Experience Camp: "Danger" is the best teacher
flowable工作流所有业务概念
MySQL - single function
The whole network is on the verge of triggering, and the all-round assistant for content distribution from media people - Rongmeibao
Apache EventMesh 分布式事件驱动多运行时
[PIMF] OpenHarmony Thesis Club - Inventory of the open source Hongmeng tripartite library [3]
每日练习------随机产生一个1-100之间的整数,看能几次猜中。要求:猜的次数不能超过7次,每次猜完之后都要提示“大了”或者“小了”。
随机推荐
multithreaded lock
Tkinter 入门之旅
【AcWing】The 62nd Weekly Match 【2022.07.30】
Made with Flutter and Firebase!counter application
The whole network is on the verge of triggering, and the all-round assistant for content distribution from media people - Rongmeibao
Taobao/Tmall get Taobao password real url API
架构师04-应用服务间加密设计和实践
华为手机一键开启“维修模式”隐藏所有数据,让手机隐私更加安全
Get Douyin Video Details API
-xms -xmx(information value)
Kotlin协程:续体、续体拦截器、调度器
保证接口数据安全的10种方式
Bika LIMS 开源LIMS集—— SENAITE的使用(检测流程)
leetcode 665. Non-decreasing Array 非递减数列(中等)
iNeuOS工业互联网操作系统,设备运维业务和“低代码”表单开发工具
Given an ip address, how does the subnet mask calculate the network number (how to get the ip address and subnet mask)
广汽本田安全体验营:“危险”是最好的老师
九齐ny3p系列语音芯片替代国产方案KT148A性价比更高420秒长度
Flex布局详解
AI 自动写代码插件 Copilot(副驾驶员)