欧几里德算法
非负整p,q的最大公约数满足下列条件:
- 如果q为0,则最大公约数是p
- 否则p,q的最大公约同时也是p%q=r和q的最大公约数
English despcription:
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.
Java代码
public static int gcd(int p, int q) {
if (q == 0)
return p;
int r = p % q;
return gcd(q, r);
}