📜  查找两个数字的LCM的Java程序

📅  最后修改于: 2020-09-26 18:49:15             🧑  作者: Mango

在此程序中,您将学习使用GCD而不是GCD查找两个数字的lcm。这是使用Java中的for和while循环完成的。

两个整数的LCM是最小的正整数,可以被两个数字完全除(无余数)。

示例1:使用while循环和if语句的LCM
public class Main {
  public static void main(String[] args) {

    int n1 = 72, n2 = 120, lcm;

    // maximum number between n1 and n2 is stored in lcm
    lcm = (n1 > n2) ? n1 : n2;

    // Always true
    while(true) {
      if( lcm % n1 == 0 && lcm % n2 == 0 ) {
        System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
        break;
      }
      ++lcm;
    }
  }
}

输出

The LCM of 72 and 120 is 360.

在此程序中,将找到其LCM的两个数字分别存储在变量n1n2中

然后,我们最初将lcm设置为两个数字中的最大值。这是因为LCM不能小于最大数量。

在无限的while循环( while(true) )内,我们检查lcm是否完美地划分了n1n2

如果是这样,我们已经找到LCM。我们打印LCM并使用break语句从while循环中break

否则,我们将lcm加1,然后重新测试除数条件。


我们还可以使用GCD通过以下公式查找两个数字的LCM:

LCM = (n1 * n2) / GCD

如果您不知道如何用Java计算GCD,请检查Java程序以找到两个数字的GCD。

示例2:使用GCD计算LCM
public class Main {
  public static void main(String[] args) {

    int n1 = 72, n2 = 120, gcd = 1;

    for(int i = 1; i <= n1 && i <= n2; ++i) {
      // Checks if i is factor of both integers
      if(n1 % i == 0 && n2 % i == 0)
        gcd = i;
    }

    int lcm = (n1 * n2) / gcd;
    System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
  }
}

该程序的输出与示例1相同。

在这里,在for循环内,我们计算两个数字-n1n2的GCD。计算后,我们使用以上公式来计算LCM。