目录
一、方法一(基础)
The algorithm is based on the below facts.
- If we subtract a smaller number from a larger one (we reduce a larger number), GCD doesn’t change. So if we keep subtracting repeatedly the larger of two, we end up with GCD.
public int gcd(int a,int b){
if(a == 0) return b;
if(b == 0) return a;
if(a == b) return a;
return a>b?gcd(a-b,b):gcd(a,b-a);
}
二、方法二(简单)
思路:递归
The algorithm is based on the below facts.
- Now instead of subtraction, if we divide the smaller number, the algorithm stops when we find the remainder 0.
public int gcd(int a,int b){
if(b == 0) return a;
return gcd(b,a%b);
}