更新时间:2022-02-20 22:52:17
递归方法是:
static int gcd(int a, int b)
{
if(a == 0 || b == 0) return a+b; // base case
return gcd(b,a%b);
}
使用while循环:
static int gcd(int a, int b)
{
while(a!=0 && b!=0) // until either one of them is 0
{
int c = b;
b = a%b;
a = c;
}
return a+b; // either one is 0, so return the non-zero value
}
当我返回 a+b
时,我实际上返回的是非零数字,假设其中一个是 0.
When I'm returning a+b
, I'm actually returning the non-zero number assuming one of them is 0.