java编程,方法调用求最大公约数和最小公倍数
时间: 2023-11-08 18:59:28 浏览: 37
好的,关于你的问题,可以通过以下代码实现:
```java
public class MathUtil {
// 求最大公约数
public static int gcd(int m, int n) {
while (n != 0) {
int temp = n;
n = m % n;
m = temp;
}
return m;
}
// 求最小公倍数
public static int lcm(int m, int n) {
return m * n / gcd(m, n);
}
}
public class Main {
public static void main(String[] args) {
int a = 20;
int b = 30;
int result1 = MathUtil.gcd(a, b);
int result2 = MathUtil.lcm(a, b);
System.out.println("最大公约数:" + result1);
System.out.println("最小公倍数:" + result2);
}
}
```
希望能够帮到你!
相关问题
用Java写出来任意输入两个数求最大公约数和最小公倍数的程序代码
可以使用辗转相除法求最大公约数,使用最大公约数求最小公倍数。
以下是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 num1 = scanner.nextInt();
System.out.print("请输入第二个数:");
int num2 = scanner.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 (b == 0) {
return a;
}
return getGcd(b, a % b);
}
// 最小公倍数 = 两数之积 ÷ 最大公约数
public static int getLcm(int a, int b, int gcd) {
return a * b / gcd;
}
}
```
以上代码中,我们首先使用Scanner类获取用户输入的两个数,然后调用getGcd方法求最大公约数,getLcm方法求最小公倍数。
Java输入两个正整数m和n,求其最大公约数和最小公倍数
输入两个正整数m和n,可以使用Java语言来求它们的最大公约数和最小公倍数。根据引用,两个整数的最大公约数等于其中较小的那个数和两数的相除余数的最大公约数。而最小公倍数等于两个数的乘积除以它们的最大公约数,根据引用。因此,可以使用一个方法来分别求出最大公约数和最小公倍数。
具体实现方法如下:
```
import java.util.Scanner;
public class GcdLcm {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("请输入第一个正整数:");
int m = scan.nextInt();
System.out.print("请输入第二个正整数:");
int n = scan.nextInt();
int gcd = getGcd(m, n);
int lcm = m * n / gcd;
System.out.println(m + "和" + n + "的最大公约数为:" + gcd);
System.out.println(m + "和" + n + "的最小公倍数为:" + lcm);
}
// 求最大公约数
public static int getGcd(int a, int b) {
if (b == 0) {
return a;
} else {
return getGcd(b, a % b);
}
}
}
```
在这个程序中,首先使用Scanner类获取用户输入的两个正整数m和n。然后,调用getGcd方法求出它们的最大公约数,再根据引用求出最小公倍数。最后,输出结果。