GCD ExGCD 扩展欧几里德算法证明与算法

#include <iostream> using namespace std; //扩展欧几里德算法 int ExGCD(int a, int b, int& x, int& y) { if(b == 0) { x = 1, y = 0; return a; } int d = ExGCD(b, a%b, x, y); int temp = x; x = y; y = temp - a/b*y; return d; } int main() { int x, y, d; d = ExGCD(99, 78, x, y); cout << d << " " << x << " " << y << endl; return 0; } //定理一: 如果a,b是不都为0的任意整数,则d=gcd(a,b)是a,b的线性组合{ax+by: x,y∈Z}的最小元素. // 已知d=gcd(a,b)=gcd(b,a mod b) // //由gcd(b,a mod b)得知,d = bx + a mod b = bx + (a-floor(a/b)*b)*y = a*y + b(x-floor(a/b)*y) //当推到gcd(a,b)时,d′ = d = a*y + b(x-floor(a/b)*y) //其他比较重要定理: //定理二:d|a, d|b => d|(ax+by) 注:d|a表示a mod b == 0,即a能被b整除 //定理一推论: 对任意整数a,b如果d|a,d|b,则d|gcd(a,b) //附: int GCD(int a, int b) {   if(b == 0)   return a;   return GCD(b, a % b); } //迭代形式: int GCD(int a, int b) { while(b != 0) { int r = b; b = a % b; a = r; } return a; }

你可能感兴趣的:(算法,扩展,include)