Google News
logo
Java Program to Find HCF and LCM of Two Numbers
To find the HCF and LCM of two numbers in Java, we need to calculate the greatest common divisor (GCD) and least common multiple (LCM) of the two numbers.

We can use the Euclidean algorithm to find the GCD, and the formula (num1 * num2) / GCD to find the LCM.

Here's the Java code :
Program :
import java.util.Scanner;

public class HCFandLCM {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the first number: ");
        int num1 = scanner.nextInt();
        System.out.print("Enter the second number: ");
        int num2 = scanner.nextInt();

        int gcd = findGCD(num1, num2);
        int lcm = (num1 * num2) / gcd;

        System.out.println("The HCF of " + num1 + " and " + num2 + " is: " + gcd);
        System.out.println("The LCM of " + num1 + " and " + num2 + " is: " + lcm);
    }

    public static int findGCD(int num1, int num2) {
        if (num2 == 0) {
            return num1;
        }
        return findGCD(num2, num1 % num2);
    }
}
Output :
Enter the first number: 45
Enter the second number: 78
The HCF of 45 and 78 is: 3
The LCM of 45 and 78 is: 1170
In this program, we first take input two numbers from the user using a Scanner object. We then call the findGCD() method to calculate the GCD of the two numbers.

The findGCD() method uses the Euclidean algorithm to find the GCD recursively. Once we have the GCD, we use the formula (num1 * num2) / GCD to find the LCM. Finally, we print the GCD and LCM of the two numbers.