当前位置:网站首页>求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);
}
}
边栏推荐
- 【AcWing】The 62nd Weekly Match 【2022.07.30】
- 常用的安全渗透测试工具(渗透测试工具)
- Jiuqi ny3p series voice chip replaces the domestic solution KT148A, which is more cost-effective and has a length of 420 seconds
- MySQL---Create and manage databases and data tables
- 35 MySQL interview questions and diagrams, this is also easy to understand
- JD.com searches for products by keyword API
- 第六章
- iNeuOS工业互联网操作系统,设备运维业务和“低代码”表单开发工具
- What's wrong with the sql syntax in my sql
- Write a database document management tool based on WPF repeating the wheel (1)
猜你喜欢
随机推荐
杰理语音芯片ic玩具芯片ic的介绍_AD14NAD15N全系列开发
Kotlin coroutines: continuation, continuation interceptor, scheduler
全平台GPU通用AI视频补帧超分教程
MySQL---聚合函数
性能优化:记一次树的搜索接口优化思路
【AcWing】第 62 场周赛 【2022.07.30】
GateWay实现负载均衡
rj45 to the connector Gigabit (Fast Ethernet interface definition)
MySQL---Create and manage databases and data tables
C# 之 扑克游戏 -- 21点规则介绍和代码实现
抖音根据关键词取视频列表 API
Shell 脚本 快速入门到实战 -02
go基础部分学习笔记记录
ojdbc8 "Recommended Collection"GAC Honda Safety Experience Camp: "Danger" is the best teacher
每月一书(202207):《Swift编程权威指南》
35 MySQL interview questions and diagrams, this is also easy to understand
linux查看redis版本命令(linux查看mysql版本号)
浅谈网络安全之算法安全
idea中搜索具体的字符内容的快捷方式









