判断素数的算法

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

 

 

 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值