ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Home » Java programs » Java basic programs

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.

Java Code Snippet - 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

ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.