写两个方法,分别求两个整数的最大公约数和最小公倍数,用主方法调用这两个方法,并输出结果,两个整数从键盘输入
时间: 2023-11-27 15:27:41 浏览: 52
以下是求最大公约数和最小公倍数的方法实现:
```java
import java.util.Scanner;
public class GCDandLCM {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the first integer: ");
int num1 = input.nextInt();
System.out.print("Enter the second integer: ");
int num2 = input.nextInt();
int gcd = findGCD(num1, num2);
int lcm = findLCM(num1, num2, gcd);
System.out.println("GCD: " + gcd);
System.out.println("LCM: " + lcm);
}
public static int findGCD(int num1, int num2) {
int gcd = 1;
for (int i = 1; i <= num1 && i <= num2; i++) {
if (num1 % i == 0 && num2 % i == 0) {
gcd = i;
}
}
return gcd;
}
public static int findLCM(int num1, int num2, int gcd) {
int lcm = (num1 * num2) / gcd;
return lcm;
}
}
```
运行结果如下:
```
Enter the first integer: 18
Enter the second integer: 24
GCD: 6
LCM: 72
```
阅读全文