今天看了下《算法》开头,里面提到一个欧几里德的算法,即
Compute the greatest common divisor of
two nonnegative integers p and q as follows:
If q is 0, the answer is p. If not, divide p by q
and take the remainder r. The answer is the
greatest common divisor of q and r.
public static int gcd(int p, int q)
{
if (q == 0) return p;
int r = p % q;
return gcd(q, r);
}
决定写下来记着,省得以后又要找。
原网址:http://www.zybang.com/question/68726aa2367ef854fc9ce3405aeb47af.html
设a、b为正整数,且a>b,a=bq+r,q、r也为正整数,且0<r<b;这里,a为被除数、b为除数、q为商、r为余数;
设a与b的最大公约数为d,即(a,b)=d,试证(b,r)=(a,b)=d?
证明: 由于(a,b)=d,所以可设a=md、b=nd,m、n为正整数,且(m,n)=1;
r=a-qb=md-qnd=d(m-qn),所以d能整除r,即d|r;由于d|b,
所以 d|(b,r)①;
假设 (b,r)=D>d②,
则D|(bq+r),即D|a,所以D|(a,b),所以D≦(a,b),即D≦d,这和②矛盾!结合①可知(b,r)=d,即(b,r)=(a,b).