判断素数的算法
来源:互联网 发布:歌词有傻瓜的网络歌曲 编辑:程序博客网 时间:2024/04/20 12:54
1.根据定义求,时间复杂度为:O(n)
判断除了1和它本身外是否还有其他因数
#include<iostream>#include<algorithm>#include<cstring>#include<cmath>#include<cstdio>#include<queue>#include<vector>using namespace std;const int MX = 1e6 + 5;int n;/** 根据定义求*/string is_Prime(int x){ if(x == 1) return "no"; bool flag = true; for(int i = 2; i < x; i++) { if(x % i == 0) { flag = false; break; } } return flag ? "yes" : "no";}int main(){ while(scanf("%d", &n) != EOF) { printf("Is %d is a prime?\t", n); cout<<is_Prime(n)<<endl; } return 0;}
#include<iostream>#include<algorithm>#include<cstring>#include<cmath>#include<cstdio>#include<queue>#include<vector>using namespace std;const int MX = 1e6 + 5;int n;/** 去掉偶数*/string is_Prime(int x){ if(x == 1) return "no"; for(int i = 3; i < x; i += 2) { if(x % i == 0) { return "no"; } } return "yes";}int main(){ while(scanf("%d", &n) != EOF) { printf("Is %d is a prime?\t", n); cout<<is_Prime(n)<<endl; } return 0;}
3.若要求n是否为素数,可以求在2-sqrt(n)中是否存在n的约数,若是不存在,在sqrt(n)-n - 1中也必定没有它的约数,时间复杂度O(sqrt(n)/2)
#include<iostream>#include<algorithm>#include<cstring>#include<cmath>#include<cstdio>#include<queue>#include<vector>using namespace std;const int MX = 1e6 + 5;int n;/** sqrt(n)*/string is_Prime(int x){ if(x == 1) return "no"; int m = sqrt(x); for(int i = 2; i <= m; i++) { if(x % i == 0) { return "no"; } } return "yes";}int main(){ while(scanf("%d", &n) != EOF) { printf("Is %d is a prime?\t", n); cout<<is_Prime(n)<<endl; } return 0;}
阅读全文
0 0
- 判断素数的算法
- 判断素数的算法
- 判断素数的算法
- 判断素数的算法
- 判断素数的算法
- 判断素数的算法
- 判断素数的算法
- 判断素数的算法
- 高效判断素数的算法
- 判断素数算法的改进
- 自己判断素数的一个算法
- java之简单的判断素数算法
- miller_rabin素数判断和pollard_rho的素数因子分解算法
- 素数判断算法-----应用
- 素数判断算法
- 快速判断素数算法
- 素数判断算法 高效率
- 常识算法--素数判断
- HashMap常见面试问题总结
- 关于JAVA接口
- 覆盖和多态的条件
- git操作
- Linux的特点
- 判断素数的算法
- BZOJ-2008 弹飞绵羊(LCT)
- Apache Security-2-Basic Authentication(基本认证)简介及实战练习
- SSM简明教程:简单的十步教你搭建人生第一个SSM框架
- JavaWeb学习总结(二)——Tomcat服务器学习和使用(一)
- 《Spring3实战》摘要(5-1)征服数据库
- 非法字符处理(替换)
- 2017 Multi-University Training Contest
- 前端性能优化----yahoo前端性能团队总结的35条黄金定律