Java 程序查找两个数字的 LCM

javaobject oriented programmingprogramming更新于 2024/4/12 5:00:17

在本文中,我们将了解如何在 Java 中计算两个数字的 LCM。两个数的最小公倍数 (LCM) 是能被两个数整除的最小正整数。

下面是相同的演示 −

输入

假设我们的输入是 −

24 和 18

输出

期望输出将是 −

两个数的最小公倍数是 72

算法

步骤 1- 开始
步骤 2- 声明三个整数:input_1、inpur_2 和 sum
步骤 3- 提示用户输入两个整数值/硬编码整数
步骤 4- 读取值
步骤 5- 使用 while 循环从 1 到其中较大的数字两个输入,检查 'i' 值是否整除两个输入而不留下余数。
步骤 6- 将 'i' 值显示为两个数字的最小公倍数
步骤 7- 停止

示例 1

import java.util.Scanner;
public class LCM {
   public static void main(String[] args) {
      int input_1 , input_2 , lcm;
      Scanner scanner = new Scanner(System.in);
      System.out.println("A scanner object has been defined ");
      System.out.println("Enter the first number: ");
      input_1 = scanner.nextInt();
      System.out.println("Enter the second number: ");
      input_2 = scanner.nextInt();
      lcm = (input_1 > input_2) ? input_1 : input_2;
      while(true) {
         if( lcm % input_1 == 0 && lcm % input_2 == 0 ) {
            System.out.printf("The LCM of %d and %d is %d.", input_1, input_2, lcm);
            break;
         }
         ++lcm;
       }
   }
}

输出

A scanner object has been defined
Enter the first number:
24
Enter the second number:
18
The LCM of 24 and 18 is 72.

示例 2

这里,整数已经被预先定义,并且它的值被访问并显示在控制台上。

public class LCM {
   public static void main(String[] args) {
      int input_1 , input_2 , lcm;
      input_1 = 24;
      input_2 = 18;
      System.out.println("The first number is " + input_1);
      System.out.println("The second number is " + input_2);
      lcm = (input_1 > input_2) ? input_1 : input_2;
      while(true) {
         if( lcm % input_1 == 0 && lcm % input_2 == 0 ) {
            System.out.printf("\nThe LCM of %d and %d is %d.", input_1, input_2, lcm);
            break;
         }
         ++lcm;
      }
   }
}

输出

The first number is 24
The second number is 18
The LCM of 24 and 18 is 72.

相关文章


有用资源