扩展欧几里得
//递归写法 int exgcd(int a, int b, int &x, int &y) { if (b == 0) { x=1; y=0; return a; } else { int ret = exgcd(b, a%b, x, y); int t = x; x = y; y = t-a/b*x; return ret; } } // 有不为0的整数a,b 则定有 gcd(a,b) = ax+by 存在,其中x, y为整数 // 常用于求解不定方程, 模的逆元, 同余方程
// 返回值是最大公约数
//非递归写法。
int exgcd2(int m, int n, int &x, int &y) { int x1, y1, x0, y0; x0 = 1; y0 = 0; x1 = 0; y1 = 1; int r = (m % n + n) % n; int q = (m - r) / n; x = 0; y = 1; while (r) { x = x0 - q * x1; y = y0 - q * y1; x0 = x1; y0 = y1; x1 = x; y1 = y; m = n; n = r; r = m % n; q = (m - r) / n; } return n; }
//欧几里得求公约数
int gcd(int a, int b) { return b==0 ? a : gcd(b, a%b); } int gcd(int a, int b) { int r = a%b; while (r) { a = b; b = r; r = a%b; } return b; }
// lcm(a,b) = a*b/gcd(a,b)