关于最大公约数的算法int gcd(int a,int b){ int t = 0; int c = 0; if(a==0) return b; if(b==0) return a; if(a { t=a; a=b; b=t; } c = a % b; while(c != 0) { a = b; b = c; c = a % b; } return b; }-------------------------------------------------- c = a % b; while(c != 0) { a = b; b = c; c = a % b; }为什么这么算能得出结果?求解释

问题描述:

关于最大公约数的算法
int gcd(int a,int b)
{
int t = 0;
int c = 0;
if(a==0)
return b;
if(b==0)
return a;
if(a {
t=a;
a=b;
b=t;
}
c = a % b;
while(c != 0)
{
a = b;
b = c;
c = a % b;
}
return b;
}
--------------------------------------------------
c = a % b;
while(c != 0)
{
a = b;
b = c;
c = a % b;
}
为什么这么算能得出结果?求解释

这是贪心算法.设最大公约数为X,则存在整数i,j使得:a = i*X,b = j*X又因为c = a % b 所以存在整数k使得:c = a-k*b = i*X - k*j*X = (i-j*k)*X即X也是c的公约数,然后a = b; b = c;如此循环,总有b = k*a的时侯,这时b...