Java Program to calculate hcf and lcm of two numbers.
Objective
Write a Java program to calculate the Highest Common Factor (HCF) and Least Common Multiple (LCM) of two numbers.
Algorithm / Approach
- Read two numbers
xandy. - Identify the greater number (
gr) and lower number (low). - Run a
whileloop as long aslow != 0. - Calculate the remainder
temp = gr % low. - Shift values:
gr = lowandlow = temp. - When the loop ends,
grholds the HCF. - Calculate LCM using the formula:
LCM = (x * y) / HCF.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter Num1: ");
int x = s.nextInt();
System.out.print("Enter Num2: ");
int y = s.nextInt();
int gr =(x >= y)?x:y;
int low =(x < y)?x:y;
int temp, lcm;
while(low!=0) {
temp = gr % low;
gr = low;
low = temp;
}
System.out.println("HCF = "+gr);
lcm = (x*y)/gr;
System.out.print("LCM = "+lcm);
}
}
Expected Output
Enter Num1: 12 Enter Num2: 15 HCF = 3 LCM = 60
Explanation of the Program
- The program implements the Euclidean algorithm to find the HCF (or GCD - Greatest Common Divisor).
- It continuously replaces the larger number with the smaller number and the smaller number with the remainder until the remainder reaches 0.
- The LCM is mathematically related to the HCF. The product of two numbers is equal to the product of their HCF and LCM.
Complexity
Time Complexity
O(log(min(x, y))) - The Euclidean algorithm is highly efficient.
Space Complexity
O(1)
Common Mistakes
- Using the modified
grandlowvalues to calculate the LCM instead of the originalxandyinputs. - Trying to find HCF by brute force checking all divisors from 1 to minimum(x, y), which is slow.