Java编写程序,计算2个非零正整数的最大公约数和最小公倍数,要求2个非零正整数从键盘输入。
时间: 2024-05-27 17:10:42 浏览: 10
import java.util.Scanner;
public class GCDandLCM {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入第一个非零正整数:");
int num1 = sc.nextInt();
System.out.print("请输入第二个非零正整数:");
int num2 = sc.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) {
int temp;
while (b != 0) {
temp = a % b;
a = b;
b = temp;
}
return a;
}
// 获取最小公倍数
public static int getLCM(int a, int b, int gcd) {
return a * b / gcd;
}
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)