Java 程序:计算两个数 LCM

原文:https://www.studytonight.com/java-programs/java-program-to-calculate-lcm-of-two-numbers

在本教程中,我们将学习如何在 java 中找到两个数字的最小公倍数(LCM)。两个整数的 LCM 被定义为可以被两个数字完全整除的最小正整数(没有余数)。但是在继续之前,如果你不熟悉 java 中循环的概念,那么一定要查看关于 Java 中循环的文章。

输入:输入第一个数字:3

输入第二个数字:5

输出:3 和 5 两个数的 LCM 为 15

Java 程序:程序 1:计算两个数 LCM

在这个程序中,我们将看到如何在不使用相同两个数的 gcd 的情况下计算两个数的 lcm。

算法:

  1. 开始
  2. 创建 Scanner 类的实例。
  3. 声明两个变量。
  4. 要求用户初始化这些变量。
  5. 声明一个变量来存储 lcm。
  6. 使用三元运算符将最大的数字赋给该变量。
  7. 使用 while 循环计算 LCM。
  8. 如果 lcm 可以被这两个数字整除,则显示 lcm。
  9. 如果条件满足,中断循环。
  10. 如果条件不满足,则增加 lcm 变量。
  11. 打印结果。
  12. 停下来。
//Java Program to Calculate the LCM of two numbers
import java.util.Scanner;  
public class Main   
{  
    public static void main(String[] args)    
    {
        //Take input from the user
        //Create an instance of the Scanner class
        Scanner sc = new Scanner(System.in); 
        System.out.println("Enter the first number: ");  
        int num1 = sc.nextInt();  
        System.out.println("Enter the second number: ");  
        int num2 = sc.nextInt();  
        int lcm = (num1 > num2) ? num1 : num2;
        // Always true
        while(true) 
        {
           if( lcm % num1 == 0 && lcm % num2 == 0 ) 
           {
               System.out.printf("The LCM of "+num1+" and "+num2+" is "+lcm);
               break;
            }
         ++lcm;
        }
   }  
}

输入第一个数字:6 输入第二个数字:12 12 和 6 的 LCM 是 12

Java 程序:程序 2:计算两个数 LCM

在这个程序中,我们将看到如何使用相同两个数的 gcd 来计算两个数的 lcm。

算法:

  1. 开始
  2. 创建 Scanner 类的实例。
  3. 声明两个变量。
  4. 要求用户初始化这些变量。
  5. 声明一个变量来存储 HCF,并将其初始化为 0。
  6. 使用 for 循环计算 GCD。
  7. 如果这两个数字都可以被循环变量整除,那么将这个数字设置为 GCD。
  8. 继续这个过程,直到找到最大的数,这个数除以两个数而没有余数。
  9. 现在,要计算 lcm,将两个数相乘,然后除以 gcd。
  10. 打印结果。
  11. 停下来。
//Java Program to Calculate the LCM of two numbers
import java.util.Scanner;  
public class Main   
{  
    public static void main(String[] args)    
    {
        //Take input from the user
        //Create an instance of the Scanner class
        Scanner sc = new Scanner(System.in); 
        System.out.println("Enter the first number: ");  
        int num1 = sc.nextInt();  
        System.out.println("Enter the second number: ");  
        int num2 = sc.nextInt();  
        //Using GCD
        int gcd = 1;
        for(int i = 1; i <= num1 && i <= num2; ++i) 
        {
            // Checks if i is factor of both integers
            if(num1 % i == 0 && num2 % i == 0)
            gcd = i;
        }
        int lcm = (num1 * num2) / gcd;
        System.out.printf("The LCM of "+num1+" and "+num2+" is "+lcm);

   }  
}

输入第一个数字:8 输入第二个数字:4 8 和 4 的 LCM 是 8