poj1811 Prime Test

时间:2023-03-09 18:56:02
poj1811 Prime Test

http://poj.org/problem?id=1811

 #include <cstdio>
#include <cstring>
#include <algorithm>
#include <ctime>
using namespace std;
typedef __int64 LL;
const int times = ;
LL minf, n; LL random(LL n){
return (double)rand() / RAND_MAX * n + 0.5;
} LL multi(LL a, LL b, LL mod){
a %= mod, b %= mod;
LL ans = ;
while(b){
if(b & ) ans += a, ans %= mod;
b >>= ;
a <<= ;
a %= mod;
}
return ans;
} LL power(LL a, LL p, LL mod){
a %= mod;
LL ans = ;
while(p){
if(p & ) ans = multi(ans, a, mod);
p >>= ;
a = multi(a, a, mod);
}
return ans;
} LL gcd(LL a, LL b){
if(!b) return a;
return gcd(b, a % b);
} bool witness(LL a, LL n){
LL u = n - ;
while(!(u & )) u >>= ;
LL t = power(a, u, n);
while(u != n - && t != && t != n - ){
t = multi(t, t, n);
u <<= ;
}
return t == n - || u & ;
} bool miller_rabin(LL n){
if(n == ) return ;
if(n < || !(n & )) return ;
//test for odd numbers larger than 2
for(int i = ; i < times; i++){
LL p = random(n - ) + ;
if(!witness(p, n)) return ;
}
return ;
} LL pollard_rho(LL n, LL t){
LL x = random(n - ) + ;
LL y = x;
LL i = , k = , d;
while(){
++i;
x = (multi(x, x, n) + t) % n;
d = gcd(y - x, n);
if( < d && d < n) return d;
if(x == y) return n;
if(i == k){
y = x;
k <<= ;
}
}
} void fact(LL n, LL t){
if(n == ) return;
if(miller_rabin(n)){
minf = min(minf, n);
return;
}
LL p = n;
while(p >= n) p = pollard_rho(p, t--);
fact(p, t);
fact(n / p, t);
} void solve(){
//if n is prime
if(miller_rabin(n)){
puts("Prime");
return;
}
//try to factorize n
//initialize the minimum non trival factor of n
minf = n;
fact(n, );
printf("%I64d\n", minf);
} int main(){
//freopen("in.txt", "r", stdin);
int T;
scanf("%d", &T);
while(T--) scanf("%I64d", &n), solve();
return ;
}