判断素数的算法
2017-08-09 10:03
155 查看
1.根据定义求,时间复杂度为:O(n)
判断除了1和它本身外是否还有其他因数
2.若该数为偶数,则必定不是素数至少可以被2整除且2为素数,时间复杂度O(n / 2)
3.若要求n是否为素数,可以求在2-sqrt(n)中是否存在n的约数,若是不存在,在sqrt(n)-n - 1中也必定没有它的约数,时间复杂度O(sqrt(n)/2)
判断除了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; }
2.若该数为偶数,则必定不是素数至少可以被2整除且2为素数,时间复杂度O(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; /** 去掉偶数 */ 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; }
相关文章推荐
- 大素数高效算法判断
- 大素数判断和素因子分解(miller-rabin,Pollard_rho算法)
- java经典算法2_判断素数
- 算法总结:判断一个数是否为素数
- js算法判断是否为素数
- 判断n以内的素数(高效算法)
- java之简单的判断素数算法
- 高效判断素数的算法
- 关于素数判断算法优化方法的讨论
- 大素数判断和素因子分解(miller-rabin,Pollard_rho算法)
- 蓝桥杯 ADV-91 算法提高 素数判断
- POJ-1811-Prime Test -(Miller_Rabin算法判断大素数, pollard_rho算法分解质因数)
- 大素数判断和素因子分解(miller-rabin,Pollard_rho算法)
- 判断一个数是否是素数的算法
- 【转】大素数判断和素因子分解【miller-rabin和Pollard_rho算法】
- 算法总结:判断一个数是否为素数
- 常用的算法:求闰年,判断素数,分解质因数,完数,水仙花数等
- JAVA基本算法面试题:2判断并输出素数
- 素数判断算法(高效率)
- 基本算法 素数判断 java