Coding Practice

Write a Java program to find LCM of two numbers

Find LCM of two numbers
Sample Output
Find LCM of two numbers.

Enter first number: 120
Enter second number: 72
GCD: 24
LCM: 360
Java-Source Code
//package loopinjava;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        int dividend, divisor, remainder = 1, lcm, dividendClone, divisorClone;

        Scanner input = new Scanner(System.in);

        System.out.println("Find LCM of two numbers.\n");

        System.out.print("Enter first number: ");
        dividend = input.nextInt();

        System.out.print("Enter second number: ");
        divisor = input.nextInt();
        
        dividendClone = dividend;
        divisorClone = divisor;
        
        while (remainder != 0) {
            remainder = dividend % divisor;
            dividend = divisor;
            divisor = remainder;
        }
        System.out.print("GCD: " + dividend + "\n");
        
        lcm = (dividendClone * divisorClone) / dividend;
 
        System.out.println("LCM: " + lcm + "\n");
    }
}
Sample Output
Find LCM of two numbers.

Enter first number: 12
Enter second number: 30
GCD: 6
LCM: 60

No comments:

Post a Comment

Change Theme
X