integcd(int a,int b,int&x,int&y){if(b ==0){
x =1;
y =0;return a;}int nx, ny;// b*nx + a%b*ny = qint q =egcd(b, a % b, nx, ny);// a*x + b*y// = a*ny + b*nx - b*(a/b)*ny// = b*nx + (a - b*(a/b))*ny// = b*nx + a%b*ny// = q
x = ny;
y = nx -(a / b)* ny;return q;}
这里如果q=1, 即上面求的x,y是对应了等式,可以求逆元
/**
* @returns (x % b + b) % b where a*x + by = gcd(a, b)
*/intmod_inv(int a,int b){int x, y;egcd(a, b, x, y);return(x % b + b)% b;// possible that x < 0}
扩展
求最小公倍数lcm (c++17中的numeric头文件也已经有了lcm这个函数)
有了最大公约数,求最小共倍数 (LCM, Least Common Multiple)就是: a * b / gcd(a, b)