Java 常见例子

LCM 代表最小公倍数。两个数的最小公倍数是可以被两个数整除的最小数。

例如 - 20 和 25 的最小公倍数是 100,30 和 40 的最小公倍数是 120。

方法是从两个数字中最大的数字开始,不断增加较大的数字,直到它可以被较小的数字整除。

示例:在没有 GCD 的情况下求两个数字的最小公倍数

在下面的示例中,要计算两个数字的 LCM,两个数字中最大的数字会自行增加,直到它可以被较小的数字整除。

public class MyClass {
  static int lcm(int x, int y) {
    int i, large, small;
    large = Math.max(x, y); 
    small = Math.min(x, y); 
    i = large;
    
    while (true) {
      if(i % small == 0)
        return i;
      i = i + large;    
    } 
  }

  public static void main(String[] args) {
    int x = 30;
    int y = 40;
    System.out.println("LCM of "+ x +" and "+ y +" is: "+ lcm(x,y));
  }
} 

上面的代码将给出以下输出:

LCM of 30 and 40 is: 120