2 条题解
-
0
P5736 【深基7.例2】质数筛——题解
解题思路
对每个数单独判断是否为质数。若 有非平凡因数,那么其中至少有一个不超过 ,所以只需试除到平方根。判断为质数后按原顺序输出。
复杂度分析
时间复杂度 ,其中 ;额外空间 。
易错点
数字 不是质数。循环条件用
1LL*i*i<=x避免乘法溢出。C++17 参考代码
#include <bits/stdc++.h> using namespace std; bool prime(int x){ if(x<2) return false; for(int i=2;1LL*i*i<=x;i++) if(x%i==0) return false; return true; } int main(){ int n;cin>>n;bool first=true; for(int i=0;i<n;i++){ int x;cin>>x; if(prime(x)){ if(!first) cout<<' '; cout<<x;first=false; } } cout<<'\n';return 0; } -
0
#include <bits/stdc++.h> using namespace std; bool prime(int x){ if(x<2) return false; for(int i=2;1LLii<=x;i++) if(x%i==0) return false; return true; } int main(){ int n;cin>>n;bool first=true; for(int i=0;i<n;i++){ int x;cin>>x; if(prime(x)){ if(!first) cout<<' '; cout<<x;first=false; } } cout<<'\n';return 0; }
- 1
信息
- ID
- 4907
- 时间
- 3000ms
- 内存
- 256MiB
- 难度
- 10
- 标签
- 递交数
- 1
- 已通过
- 1
- 上传者
粤公网安备44195502000195号