bzoj3667 Rabin-Miller算法

229 篇文章 0 订阅

标题写错了,其实这题考pollard-rho。

#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
#define LL long long
int prm[]={2,3,5,7,11,13,17,19,23};
LL Rand(LL n)
{
    return rand()%(n-1)+1;
}
LL dec(LL x,LL y,LL p)
{
    x-=y;
    return x<0?x+p:x;
}
LL inc(LL x,LL y,LL p)
{
    unsigned LL ret=(unsigned LL)x+y;
    return ret>=p?ret-p:ret;
}
LL mul(LL x,LL y,LL p)
{
    LL ret=0;
    for (;y;y>>=1,x=inc(x,x,p))
        if (y&1) ret=inc(ret,x,p);
    return ret;
}
LL pow(LL x,LL y,LL p)
{
    LL ret=1;
    for (;y;y>>=1,x=mul(x,x,p))
        if (y&1) ret=mul(ret,x,p);
    return ret;
}
LL gcd(LL x,LL y)
{
    return y?gcd(y,x%y):x;
}
/*inline bool check(LL n) {
    if( n == 2 || n == 3 || n == 5 ) return 1;
    if( n < 2 || !(n&1) || n % 3 == 0 || n % 5 == 0 ) return 0;
    LL m = n - 1; int k = 0;
    while( !(m & 1) ) m >>= 1, k++;
    for (int i=1;i<=5;i++) {
        LL x = pow(rand() % (n-1) + 1,m,n), y;
        for (int j=1;j<=k;j++) {
            y = mul(x,x,n);
            if( y == 1 && x != 1 && x != n - 1 ) return 0;
            x = y;
        }
        if( y != 1 ) return 0;
    }
    return 1;
}*/
inline int check(LL n)
{
    /*for (int i=0;i<=3;i++)
    {
        if (n==prm[i]) return 1;
        if (n%prm[i]==0) return 0;
    }*/
    /*if (n==2||n==3||n==5) return 1;
    if (n<=1||(n&1)==0||n%2==0||n%3==0||n%5==0) return 0;*/
    LL x=n-1,k=0,y,z;
    while (!(x&1)) x>>=1,k++;
    for (int i=1;i<=5;i++)
    {
        y=pow(Rand(n),x,n);
        for (int j=1;j<=k;j++)
        {
            z=mul(y,y,n);
            if (z==1&&y!=1&&y!=n-1) return 0;
            y=z;
        }
        if (y!=1) return 0;
    }
    return 1;
}
LL solve(LL n)
{
    if (check(n)) return n;
    LL x=Rand(n),y,c=Rand(n),d;
    y=x;
    for (int i=1,k=1;;i++)
    {
        x=inc(mul(x,x,n),c,n);
        d=gcd(dec(x,y,n),n);
        if (d==n) return solve(n);
        if (d>1) return max(solve(d),solve(n/d));
        if (i==k) k<<=1,y=x;
    }
}
int main()
{
    srand(321453);
    int T;
    LL n,ans;
    scanf("%d",&T);
    while (T--)
    {
        scanf("%lld",&n);
        ans=solve(n);
        if (ans==n) printf("Prime\n");
        else printf("%lld\n",ans);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值