Java - Calculate LCM (Least Common Multiple) using Java Program

In this code snippet, we will find the LCM of given numbers using Java program.

LCM can be defined as any common multiple except 1, then it will always be greater than or equal to the maximum number. It cannot be less than it. LCM of two numbers is a number which is a multiple of both the numbers.

Calculate LCM (Least Common Multiple) of Numbers using Java Program

import java.util.Scanner;
 
public class Lcm {
  
    //  Lowest common Number
    public static int lcm(int First_number, int Second_number) {
        int x,max=0,min=0,lcm=0;
        if(First_number>Second_number)
        {
            max=First_number;
            min=Second_number;
        }
        else
        {
            max=Second_number;
            min=First_number;
        }
          
     
          
        for(int i=1;i<=min;i++)
           {
            x=max*i; 
            if(x%min==0) 
             {
              lcm=x; 
              break; 
             }
            }
         return lcm;
    }
  
    public static void main(String[] args) {
      
        Scanner sc=new Scanner(System.in);
 
        System.out.print("First Number  :");
        int num1=sc.nextInt();
        System.out.print("Second Number :");
        int num2=sc.nextInt();
 
        System.out.println("Lowest Common Factor: " + lcm(num1,num2));
       
    }
}

Output


    First Number  :24
    Second Number :16
    Lowest Common Factor: 48

Java Basic Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.