poj 3243 Clever Y 高次方程

  1  Accepted    8508K     579MS   C++    2237B/**
hash的强大,,还是高次方程,不过要求n不一定是素数
**/
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
long long a,b,n;
const int maxn = ;
bool Hash[maxn];
long long val[maxn];
long long idx[maxn]; long long gcd(long long a,long long b){
if(b==)
return a;
return gcd(b,a%b);
} void ex_gcd(long long a,long long b,long long &x,long long &y){
if(b==){
x=;
y=;
return ;
}
ex_gcd(b,a%b,x,y);
long long tmp= x-(a/b)*y;
x = y;
y = tmp;
return ;
} void Insert(long long id,long long num){
long long k = num%maxn;
while(Hash[k]&&val[k]!=num){
k++;
if(k==maxn) k = k-maxn;
}
if(!Hash[k]){
Hash[k] = true;
val[k] = num;
idx[k] = id;
}
return;
} long long found(long long num){
long long k = num%maxn;
while(Hash[k]&&val[k]!=num){
k++;
if(k==maxn) k-=maxn;
}
if(Hash[k]){
return idx[k];
}
return -;
} long long baby_step(long long a,long long b,long long n){
long long temp =;
long long i;
for(i=;i<=;i++){
if(temp==b%n) return i;
temp = temp*a%n;
}
long long tmp,d =,cnt=;
memset(Hash,false,sizeof(Hash));
memset(val,-,sizeof(val));
memset(idx,-,sizeof(idx)); while((tmp=gcd(a,n))!=){
if(b%tmp)
return -;
cnt++;
n = n/tmp;
b = b/tmp;
d =d*a/tmp%n;
}
long long cur =;
long long m = ceil(sqrt(n+0.5));
for(i=;i<m;i++){
Insert(i,cur);
cur = cur*a%n;
}
long long x,y;
for(i=;i<m;i++){
ex_gcd(d,n,x,y);
x = x*b%n;
x = (x%n+n)%n;
long long k = found(x);
if(k!=-)
return i*m+k+cnt;
d = d*cur%n;
}
return -;
} int main()
{
while(scanf("%I64d%I64d%I64d",&a,&n,&b)==){
if(a==&&b==&&n==)
break;
long long res = baby_step(a,b,n);
if(res==-){
printf("No Solution\n");
}else{
printf("%I64d\n",res);
}
}
return ;
}
上一篇:.NET环境配置(二)


下一篇:解决Jenkins安装的时区问题