您的位置:首页 > 其它

判断素数的算法

2017-08-09 10:03 155 查看
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;
}


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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: