java求两个数的最大公约数和最小公倍数
时间: 2023-04-17 17:00:55 浏览: 80
求两个数的最大公约数(Greatest Common Divisor, GCD)可以使用辗转相除法(Euclidean algorithm),如下:
```java
int gcd(int a, int b) {
if (b == 0) return a;
else return gcd(b, a % b);
}
```
求两个数的最小公倍数(Least Common Multiple, LCM)可以使用下面的公式:
```java
int lcm(int a, int b) {
return a * b / gcd(a, b);
}
```
这里使用了最大公约数来求最小公倍数。
相关问题
数据结构java求两个数最小公倍数和最大公约数
求两个数的最小公倍数可以通过它们的乘积除以它们的最大公约数得到,而求最大公约数可以使用辗转相除法。
以下是Java代码实现:
```java
public class Main {
public static void main(String[] args) {
int a = 12, b = 18;
int gcd = getGCD(a, b);
int lcm = getLCM(a, b, gcd);
System.out.println("最大公约数:" + gcd);
System.out.println("最小公倍数:" + lcm);
}
// 辗转相除法求最大公约数
public static int getGCD(int a, int b) {
if (b == 0) {
return a;
}
return getGCD(b, a % b);
}
// 求最小公倍数
public static int getLCM(int a, int b, int gcd) {
return a * b / gcd;
}
}
```
输出结果为:
```
最大公约数:6
最小公倍数:36
```
java求两数最大公约数和最小公倍数
最大公约数和最小公倍数是数学中的基础概念,在Java中可以通过以下代码进行计算:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = input.nextInt();
int gcd = getGCD(num1, num2);
int lcm = getLCM(num1, num2, gcd);
System.out.println("最大公约数为:" + gcd);
System.out.println("最小公倍数为:" + lcm);
}
// 求两数最大公约数
public static int getGCD(int a, int b) {
if (a % b == 0) {
return b;
} else {
return getGCD(b, a % b);
}
}
// 求两数最小公倍数
public static int getLCM(int a, int b, int gcd) {
return a * b / gcd;
}
}
```
输入两个数字后,程序会输出它们的最大公约数和最小公倍数。
笑话:为什么马路会斜呢?因为一条腿长一条腿短。
相关推荐
![](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)