求最大公约数
int gcd(int m, int n) { int r, mid; if (m < n) { mid = m; m = n; n = mid; } while ((r = m%n) != 0) { m = n; n = r; } return n; }
求最大公约数d,并求出am+bn=d中a和b
int gcd(int m, int n, int &a, int &b) { int a1, b1, mid, q, r; bool fGreater = (m >= n); if (!fGreater) { mid = m; m = n; n = mid; } a1 = b = 1; a = b1 = 0; while ((r = m%n) != 0) { q = m / n; //得到相应项数值 m = n; n = r; mid = a1; a1 = a; a = mid - q*a; mid = b1; b1 = b; b = mid - q*b; } if (!fGreater) { mid = a; a = b; b = mid; } return n; }
所有代码均经过测试,结果正确。