poj 1811 Prime Test(大素数判断+素因子判断)

题目链接:http://poj.org/problem?id=1811

题意:判断一个数是否为素数,如果不是则找到它最小的素数因子。

思路:因为n很大,不好打表处理,用miller_rabin判断n是否为素数,再用Pollard_rho算法找素数因子。

代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <map>
#include <vector>
#include <math.h>
using namespace std;
#define ll long long
const int N=1e6+10;
ll mul(ll a,ll b,ll n)
{
    ll ans=0;
    while(b)
    {
        if(b&1)ans=(ans+a)%n;
        a=(a+a)%n;
        b>>=1;
    }
    return ans;
}
ll poww(ll a,ll b,ll n)
{
    ll ans=1;
    while(b)
    {
        if(b&1)ans=mul(ans,a,n);
        a=mul(a,a,n);
        b>>=1;
    }
    return ans;
}
bool miller_rabin(ll n)
{
    ll t,u,a,x,y;
    if(n==2)return true;
    if(n==1||!(n&1))return false;
    for(t=0,u=n-1;!(u&1);t++,u>>=1);
    for(int i=0;i<20;i++)
    {
        ll a=rand()%(n-1)+1;
        x=poww(a,u,n);
        for(int j=0;j<t;j++)
        {
            y=mul(x,x,n);
            if(y==1&&x!=1&&x!=n-1)
                return false;
            x=y;
        }
        if(x!=1)
            return false;
    }
    return true;
}
ll yz[N];
int cnt;
ll gcd(ll a,ll b)
{
    if(a<0)return gcd(-a,b);
    if(a==0)return 1;
     while(b)
    {
        long long int t=a%b;
        a=b;
        b=t;
    }
    return a;
}
ll Pollard_rho(ll n,ll c)
{
    int i=1,k=2;
    ll x=rand()%(n-1)+1;
    ll y=x;
    while(1)
    {
        i++;
        x=(mul(x,x,n)+c)%n;
        ll p=gcd(y-x,n);
        if(p!=1&&p!=n)
            return p;
        if(y==x)
            return n;
        if(i==k)
        {
            y=x;
            k+=k;
        }
    }
}
void findx(ll n)
{
    if(n==1)return ;
    if(miller_rabin(n))
    {
        yz[cnt++]=n;
        return;
    }
    ll p=n;
    while(p>=n)
        p=Pollard_rho(p,rand()%(n-1)+1);
    findx(p);
    findx(n/p);
}
int main()
{
    ll n;
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%lld",&n);
        if(miller_rabin(n))
        {
             printf("Prime\n");
        }
        else
        {
            cnt=0;
            findx(n);
            ll ans=yz[0];
            for(int i=1;i<cnt;i++)
                ans=min(ans,yz[i]);
            printf("%lld\n",ans);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/imzxww/article/details/81029721