最简单的方法求输入的两个整数的最大公约数和最小公倍数。Java
时间: 2024-05-14 19:17:08 浏览: 49
可以使用辗转相除法求最大公约数,使用两数的积除以最大公约数求最小公倍数。以下是Java代码实现:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入两个整数:");
int a = scanner.nextInt();
int b = scanner.nextInt();
int temp;
int m = a * b;
while (b != 0) {
temp = a % b;
a = b;
b = temp;
}
int n = m / a;
System.out.println("最大公约数:" + a);
System.out.println("最小公倍数:" + n);
}
}
```
输入示例:
```
请输入两个整数:12 16
```
输出示例:
```
最大公约数:4
最小公倍数:48
```
相关问题
最简单的方法求给定两个整数的最大公约数和最小公倍数。Java
可以使用辗转相除法来求两个整数的最大公约数,使用最大公约数和两个整数的乘积来求最小公倍数。
Java代码如下:
```java
public class GCDAndLCM {
// 求最大公约数
public static int gcd(int a, int b) {
if (a == 0) {
return b;
}
return gcd(b % a, a);
}
// 求最小公倍数
public static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
// 测试
public static void main(String[] args) {
int a = 12;
int b = 18;
System.out.println("最大公约数:" + gcd(a, b));
System.out.println("最小公倍数:" + lcm(a, b));
}
}
```
输出结果为:
```
最大公约数:6
最小公倍数:36
```
java中,输入两个正整数,求其最大公约数和最小公倍数。最简单的办法
使用辗转相除法来求解最大公约数,使用两数相乘再除以最大公约数来求解最小公倍数。
具体实现代码如下:
```java
import java.util.Scanner;
public class GcdLcm {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入第一个正整数:");
int num1 = scanner.nextInt();
System.out.print("请输入第二个正整数:");
int num2 = scanner.nextInt();
// 求最大公约数
int gcd = getGcd(num1, num2);
System.out.println(num1 + "和" + num2 + "的最大公约数是:" + gcd);
// 求最小公倍数
int lcm = num1 * num2 / gcd;
System.out.println(num1 + "和" + num2 + "的最小公倍数是:" + lcm);
}
// 辗转相除法求最大公约数
public static int getGcd(int num1, int num2) {
if (num2 == 0) {
return num1;
} else {
return getGcd(num2, num1 % num2);
}
}
}
```
输入输出示例:
```
请输入第一个正整数:24
请输入第二个正整数:36
24和36的最大公约数是:12
24和36的最小公倍数是:72
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)