目录
一、方法一(基础)
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);
}
博客介绍了求最大公约数(GCD)的两种方法。方法一基于Euclidean algorithm,通过大数减小数,不断重复此操作直至得到GCD;方法二则采用递归,用大数除以小数,当余数为0时算法停止。
1080

被折叠的 条评论
为什么被折叠?



