帮我分析以下代码。public static int gcd(int a, int b) { 2. if (a > b) { 3. return gcd(a-b, b); 4. } else if (b > a) { 5. return gcd(a, b-a); 6. } 7. return a; 8. }
时间: 2023-07-15 18:11:54 浏览: 44
这是一个计算两个整数的最大公约数(GCD)的递归函数。函数名为gcd,接受两个参数a和b。
首先,第2行检查a是否大于b。如果是,则将a-b和b作为新参数调用gcd函数(递归调用),并将结果返回。
如果第2行的条件不成立,则执行第4行的else if块,检查b是否大于a。如果是,则将a和b-a作为新参数调用gcd函数(递归调用),并将结果返回。
否则,执行第7行的return语句,返回a作为最大公约数。
这个函数使用递归的方式不断缩小两个数的差距,直到它们相等,然后返回其中一个数作为最大公约数。
相关问题
public static int gcd(int m, int n) 还可以怎么写
`public static int gcd(int m, int n)` 这个方法还可以使用递归来实现。递归方法的基本思路是:如果 m 小于 n,就交换 m 和 n 的值;然后,如果 n 等于 0,就返回 m,否则递归调用 `gcd(n, m % n)`。
下面是使用递归方式实现的代码:
```
public static int gcd(int m, int n) {
if (m < n) {
int temp = m;
m = n;
n = temp;
}
if (n == 0) {
return m;
} else {
return gcd(n, m % n);
}
}
```
递归实现的方式与循环实现的方式相比,代码看起来更加简洁,但是在计算过程中会生成多个调用栈,可能会导致栈溢出的问题。因此,在实际应用中需要注意函数的递归深度。
public class MathUtil { public int f(int a, int b) { if (b == 0) { return a; } else { return f(b, a % b); } }}public class LCMUtil extends MathUtil { @Override public int f(int a, int b) { int m = super.f(a, b); return (a * b) / m; }}public class Main { public static void main(String[] args) { MathUtil mathUtil = new MathUtil(); int gcd = mathUtil.f(12, 18); System.out.println("12和18的最大公约数是:" + gcd); LCMUtil lcmUtil = new LCMUtil(); int lcm = lcmUtil.f(12, 18); System.out.println("12和18的最小公倍数是:" + lcm); }}完整java语句
完整的 Java 语句如下:
```
public class MathUtil {
public int f(int a, int b) {
if (b == 0) {
return a;
} else {
return f(b, a % b);
}
}
}
public class LCMUtil extends MathUtil {
@Override
public int f(int a, int b) {
int m = super.f(a, b);
return (a * b) / m;
}
}
public class Main {
public static void main(String[] args) {
MathUtil mathUtil = new MathUtil();
int gcd = mathUtil.f(12, 18);
System.out.println("12和18的最大公约数是:" + gcd);
LCMUtil lcmUtil = new LCMUtil();
int lcm = lcmUtil.f(12, 18);
System.out.println("12和18的最小公倍数是:" + lcm);
}
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)