扩展欧几里得算法总结
解方程:ax+by=c即ax≡c (mod b)
先上代码
#include<cstdio> long long gcd(long long a,long long b,long long &x,long long &y) { if(!b) { x=1;y=0;return a; } int d=gcd(b,a%b,y,x);y-=x*(a/b); return d; } int main() { long long a,b,x,y,c; scanf("%lld %lld %lld %lld %lld",&a,&b,&x,&y,&c); long long d=gcd(a,b,x,y); if(c%d) printf("Impossible\n"); else { x*=(c/d); printf("%lld\n",x); } return 0; }
通解:
x = x0 + (b/gcd)*t
y = y0 – (a/gcd)*t
最小解:
int l=abs(b/gcd); //防止b为负数
x=(x0%l+l)%l; //注意:abs不能处理long long ,先强制转为int
逆元:
即c==1时
即ax+by=1(gcd(a,b)==1)时
该方程的唯一解(方程解的个数为gcd(a,b),前提:有解即c%gcd(a,b)==0)
参考资料:
http://www.acmerblog.com/extend-gcd-5610.html
http://blog.csdn.net/zhjchengfeng5/article/details/7786595