求最小公倍数java
时间: 2023-11-21 20:52:40 浏览: 39
求最小公倍数的方法有多种,其中一种常用的方法是先求出两个数的最大公约数,然后用两个数的乘积除以最大公约数即可得到最小公倍数。以下是一个Java实现的例子:
```
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;
while (c != 0) {
a = b;
b = c;
c = a % b;
}
System.out.println(a * s.nextInt() / b);
}
}
```
这个例子中,我们先输入两个正整数A和B,然后用辗转相除法求出它们的最大公约数,最后用两个数的乘积除以最大公约数得到最小公倍数。
相关问题
Java求最小公倍数
以下是三种Java求最小公倍数的方法:
1. 最简单粗暴的方式是一个个试,从1开始逐个判断是否同时是x和y的倍数,直到找到最小公倍数为止。
```java
public int lcm(int x, int y) {
for (int i = 1; i < x * y; i++) {
if (i % x == 0 && i % y == 0)
return i;
}
return x * y;
}
```
2. 如果已经求出了最大公约数gcd,那么最小公倍数可以通过x和y的乘积除以gcd得到。
```java
public int lcm2(int x, int y) {
return x * y / gcd1(x, y);
}
```
3. 如果x和y比较大的话,可能会导致溢出,可以使用下面的写法,先求出最大公约数gcd,然后通过(x / gcd) * (y / gcd) * gcd计算最小公倍数。
```java
public int lcm3(int x, int y) {
int gcd = gcd1(x, y);
return (x / gcd) * (y / gcd) * gcd;
}
```
java求最小公倍数
要在Java中求最小公倍数,可以使用最大公约数来计算。可以使用辗转相除法来求最大公约数,然后使用公式最小公倍数=两整数的乘积/最大公约数来求解最小公倍数。以下是一个示例代码:
```java
public int lcm(int x, int y) {
int gcd = gcd(x, y);
return x * y / gcd;
}
public int gcd(int x, int y) {
while (y != 0) {
int temp = x % y;
x = y;
y = temp; }
return x;
}
```
相关推荐
![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)