码迷,mamicode.com
首页 > 其他好文 > 详细

判断一个数是否是素/质数

时间:2018-07-23 19:13:34      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:pre   int   sqrt   +=   ret   左右   不为   -o   return   

垃圾版本 对从2到n-1取模,不为0则是素数,O(N)

bool judge(ll n)
{
    if(n==2||n==3) return true;
    for(int i=2;i<n;i++)
        if(n%i==0) return false;
    return true;
}

普通版本 对从2到sqrt(n)取模,不为0则是素数, O(logN)

bool judge(ll n)
{
    if(n==2||n==3) return true;
    for(int i=2;i<=sqrt(n);i++)
        if(n%i==0) return false;
    return true;
}

高配版本 先对2取模,然后开始对3到sqrt(n)的奇数取模 ,O(0.5*logN)

bool judge(ll n)
{
    if(n==2||n==3) return true;
        if(n%2==0) return false;
    for(int i=3;i<=sqrt(n);i+=2)
        if(n%i==0) return false;
    return true;
}

至尊版本 因为素数只在6的倍数的左右两边,所以先对6取模,看是不是1和5,然后在对5+i6,到sqrt(n)取模, O(0.167logN)

bool judge(ll n)
{
    if(n==2||n==3) return true;
    if(n%6!=1&n%6!=5) return false;
    double x=(double)sqrt(n);
    for(int i=5;i<=x;i+=6)
    if(n%i==0||n%(i+2)==0) return false ;
    return true;
}

判断一个数是否是素/质数

标签:pre   int   sqrt   +=   ret   左右   不为   -o   return   

原文地址:https://www.cnblogs.com/wzl19981116/p/9356273.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!