數論——擴展的歐幾裏德算法 - HDU2669
阿新 • • 發佈:2019-01-23
target idt sin ios tar eight str 遞歸 sorry
http://acm.hdu.edu.cn/showproblem.php?pid=2669
#include <iostream> using namespace std; int gcd(int a, int b, int &x, int &y) { if (b == 0) { x = 1, y = 0; return a; } int q = gcd(b, a%b, y, x); y -= a / b * x; return q; } int main() { int a, b;while (scanf("%d%d", &a, &b) != EOF) { int x, y; if (gcd(a, b, x, y) != 1) cout << "sorry" << endl; else { if (x < 0) { x += b; y -= a; } cout << x << " " << y << endl; } }return 0; }
這裏的x2,y2是遞歸返回階段,上一層的y和x,所以代碼中的是y-=a/b*x。
以21/8為示例,返回階段遞歸示意圖。
題目要求X必需為非負數,最後這個是很容易忽略掉的,很好看懂,但是寫題目的時候沒有想到可以這樣寫。
數論——擴展的歐幾裏德算法 - HDU2669