java代码求两个数的最大公约数和最小公倍数
时间: 2023-11-17 15:14:25 浏览: 94
最大公约数代码:
```java
public static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
```
最小公倍数代码:
```java
public static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
```
完整代码:
```java
public class Main {
public static void main(String[] args) {
int a = 12;
int b = 18;
int gcd = gcd(a, b);
int lcm = lcm(a, b);
System.out.println("最大公约数:" + gcd);
System.out.println("最小公倍数:" + lcm);
}
public static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
}
```
阅读全文