判断素数的算法

来源:互联网 发布:歌词有傻瓜的网络歌曲 编辑:程序博客网 时间:2022/05/28 05:06

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;}



原创粉丝点击