java最大公约数与小公倍数
时间: 2024-04-10 09:33:21 浏览: 17
Java中求最大公约数和最小公倍数可以使用辗转相除法和最小公倍数公式来实现。
首先,我们来求最大公约数。使用辗转相除法,不断地用较小数去除较大数,直到余数为0为止。最后的除数就是最大公约数。
以下是一个示例代码:
```java
public class GCDandLCM {
public static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static int lcm(int a, int b) {
return a * b / gcd(a, b);
}
public static void main(String[] args) {
int num1 = 12;
int num2 = 18;
int gcdValue = gcd(num1, num2);
int lcmValue = lcm(num1, num2);
System.out.println("最大公约数:" + gcdValue);
System.out.println("最小公倍数:" + lcmValue);
}
}
```
输出结果为:
```
最大公约数:6
最小公倍数:36
```
以上代码中,gcd方法用于求最大公约数,lcm方法用于求最小公倍数。在main方法中,我们给出了两个示例数num1和num2,并调用gcd和lcm方法来计算最大公约数和最小公倍数。最后,通过打印输出结果来展示计算结果。
希望以上代码能帮助到你!如果有任何疑问,请随时提出。