๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

WAP to find the LCM of two numbers in Java  


What is LCM ?
  • LCM (Least Common Multiple) is the smallest number that is a multiple of two or more numbers.
  • For example:
    Find LCM of 4 and 6:
    • Multiples of 4: 4, 8, 12, 16, 20
    • Multiples of 6: 6, 12, 18, 24
    • LCM = 12 (smallest common multiple)
Logical Steps:
  • Take two numbers to find their LCM.
  • Determine the larger number between the two.
  • Use a loop to check multiples of the larger number.
  • In each iteration:
    • Check if the current multiple is divisible by both numbers.
    • If true, it is the LCM; stop the loop.
  • Return the first common multiple as the LCM.
Programs:
  • Below is the simple program:
    public class LcmOfTwoNumbers
    {
        public static void main(String[] args)
        {
            int no1 = 12, no2 = 15;
            int lcm = no1;
    
            if (no2 > no1)
            {
                lcm = no2;
            }
    
            while (true)
            {
                if (lcm % no1 == 0 && lcm % no2 == 0)
                {
                    System.out.println("LCM: " + lcm);
                    break;
                }
                lcm++;
            }
        }
    }
    Output:
    LCM: 60
  • Below is the program by taking user input:
    import java.util.Scanner;
    
    public class LcmOfTwoNumbers
    {
        public static void main(String[] args)
        {
            Scanner scanner = new Scanner(System.in);
    
            System.out.print("Enter no1: ");
            int no1 = scanner.nextInt();
    
            System.out.print("Enter no2: ");
            int no2 = scanner.nextInt();
    
            int lcm = no1;
    
            if (no2 > no1)
            {
                lcm = no2;
            }
    
            while (true)
            {
                if (lcm % no1 == 0 && lcm % no2 == 0)
                {
                    System.out.println("LCM: " + lcm);
                    break;
                }
                lcm++;
            }
        }
    }
    Output:
    Enter no1: 20
    Enter no2: 25
    LCM: 100
Program Explanation
  • Initialize two numbers:
    • no1 = 12 and no2 = 15.
  • Find the larger number:
    • This will be the starting point to find the LCM.
      • int lcm = no1;
        if (no2 > no1) {
            lcm = no2;
        }
      • This sets lcm to the larger of the two numbers.
  • Use a while loop to check if lcm is divisible by both numbers.
    • If lcm % no1 == 0 and lcm % no2 == 0, it is the LCM.
    • Print the LCM and exit the loop using break.
  • If not divisible, increment lcm by 1 and repeat until you find the LCM.