java求两个数的公倍数的代码
时间: 2023-03-06 20:17:21 浏览: 56
答:可以使用以下代码求两个数的公倍数:int a, b, c; int min, max; if (a>b) { max = a; min = b; } else { max = b; min = a; } for (int i=1; i<max; i++) { c = min*i; if (c%max == 0) { System.out.println("公倍数为:" + c); break; } }
相关问题
java求三个数的最小公倍数
可以使用以下方法求三个数的最小公倍数:
1. 首先求出其中任意两个数的最小公倍数,可以使用以下代码:
```java
public static int lcm(int a, int b) {
return a * b / gcd(a, b);
}
public static int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
```
其中,`lcm` 方法用于求两个数的最小公倍数,`gcd` 方法用于求两个数的最大公约数。这两个方法可以用于求任意两个数的最小公倍数。
2. 然后再将得到的最小公倍数和第三个数求最小公倍数,同样使用 `lcm` 方法即可。
以下是求解三个数的最小公倍数的完整代码实现:
```java
public static int lcm(int a, int b) {
return a * b / gcd(a, b);
}
public static int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
public static int lcm(int a, int b, int c) {
return lcm(lcm(a, b), c);
}
```
使用示例:
```java
int a = 2, b = 3, c = 4;
int result = lcm(a, b, c);
System.out.println(result); // 输出 12
```
java两个数的最小公倍数
Java中计算两个数的最小公倍数可以使用辗除法来实现。具体的代码实现可以参考以下两种格式:
格式1:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int a = s.nextInt();
int b = s.nextInt();
int c = a % b;
long d = (long) a * (long) b;
while (c != 0) {
a = b;
b = c;
c = a % b;
}
System.out.println(d / b);
}
}
格式2:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int a = s.nextInt();
int b = s.nextInt();
int c = b;
long d = (long) a * (long) b;
while (a % b != 0) {
c = a % b;
a = b;
b = c;
}
System.out.println(d / c);
}
}
以上两种格式都可以用来计算两个数的最小公倍数,可以根据自己的喜好选择其中一种来使用。
相关推荐
![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)