您的位置:首页 > 其它

poj 1811 Prime Test(大素数判定)

2014-04-15 12:36 417 查看
Prime Test

Time Limit: 6000MSMemory Limit: 65536K
Total Submissions: 28142Accepted: 7044
Case Time Limit: 4000MS
Description

Given a big integer number, you are required to find out whether it's a prime number.

Input

The first line contains the number of test cases T (1 <= T <= 20 ), then the following T lines each contains an integer number N (2 <= N < 254).

Output

For each test case, if N is a prime number, output a line containing the word "Prime", otherwise, output a line containing the smallest prime factor of N.

Sample Input
2
5
10


Sample Output
Prime
2


Source

POJ Monthly

题意:判断一个数是否素数,否的话输出其最小的因子

题解:用miller大素数判定,和pollar求因子

#include<iostream>
#include<cstdlib>
#include<ctime>
#include<cmath>
#define TIME 8
#define C 50
#define MAX (pow(2.0,60))
using namespace std;
long long MIN;
long long gcd(long long a,long long b)
{
if(!b) return a;
return gcd(b,a%b);
}
long long mod_mult(long long a,long long b,long long mod)
{
long long s=0;
a=a%mod;
while(b)
{
if(b&1)
{
s+=a;
if(s>=mod) s-=mod;
}
a=a<<1;
if(a>=mod) a-=mod;
b=b>>1;
}
return s;
}
long long mod_pow(long long a,long long b,long long mod)
{
long long d=1;
a=a%mod;
while(b)
{
if(b&1) d=mod_mult(d,a,mod);
a=mod_mult(a,a,mod);
b=b>>1;
}
return d;
}
bool wintess(long long a,long long n)
{
long long m=n-1,x,y;
int i,j=0;

while(m%2==0) m>>=1,j++;
x=mod_pow(a,m,n);
for(i=1; i<=j; i++)
{
y=mod_pow(x,2,n);
if((y==1)&&(x!=1)&&(x!=n-1)) return true;
x=y;
}
if(y!=1) return true;
return false;
}
bool miller_rabin(int times,long long n)
{
long long a;
if(n==1) return false;
if(n==2) return true;
if(n%2==0) return false;
srand(time(NULL));
for(int i = 1 ; i<=times; i++)
{
a=rand()%(n-1)+1;
if(wintess(a,n)) return false;
}
return true;
}
long long pollard(long long n,int c)
{
long long i=1,k=2,x,y,d,tot=1<<15;

srand(time(NULL));
y=x=rand()%n;
while(true)
{
i++;
x=(mod_mult(x,x,n)+c)%n;
d=gcd(y-x,n);
if(d>1&&d<n) return d;
if(y==x) return n;
if(i==k)
{
y=x;
k=k<<1;
}
tot--;
if(!tot) return n;
}
}
void get_small(long long n,int c)
{
long long m;

if(n==1) return;
if(miller_rabin(TIME,n))
{
if(n<MIN) MIN=n;
return;
}
m=n;
while(m==n) m=pollard(n,c--);
get_small(m,c);
get_small(n/m,c);
}
int main()
{
long long n;
int t;

ios::sync_with_stdio(false);
cin >> t;
while(t--)
{
cin >> n;
if(n==2||miller_rabin(TIME,n)) cout << "Prime\n";
else if(n%2==0)
{
cout << "2\n";
}
else
{
MIN=MAX;
get_small(n,C);
cout << MIN << endl;
}
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: