您的位置:首页 > 其它

扩展欧几里得算法——pku1061

2011-04-26 21:50 267 查看
直接用欧几里得
AX+BY=gcd(A,B);

问题里s(n-m)+k*l=x-y
所以存在s,k的整数解的话就要 (x-y)%gcd(n-m,l)
再分情况考虑n-m是否是正负 枚举k得出解

View Code

#include<stdio.h>

__int64 Ext_gcd(__int64 a,__int64 b,__int64 &x,__int64 &y)
{
if(b==0) { x=1, y=0; return a; }
__int64 res= Ext_gcd(b,a%b,y,x);
y-= a/b*x;
return res;
}
__int64 Ax_b_mod_n(__int64 a,__int64 b,__int64 n)//同余方程 (m-n)*t = (y-x) (mod L) 的最小正整数解
{
__int64 res,x,y,t;
res= Ext_gcd(a,b,x,y);
if(n%res==0)
{
x= x*n/res;
t= b/res;
if(t<0) t=-t;
x= (x%t+t)%t;
return x;
}
return -1;
}
int main()
{
__int64 x,y,m,n,len,t;
scanf("%I64d%I64d%I64d%I64d%I64d",&x,&y,&m,&n,&len);
t= Ax_b_mod_n(m-n,len,y-x);
if(t==-1) printf("Impossible\n");
else printf("%I64d\n",t);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: