**HCF and LCM in Java**

Here you will get a program code to calculate **HCF and LCM in Java** programming.

## What is HCF and LCM?

**HCF (Highest Common Factor)**:

HCF, also known as GCD (Greatest Common Divisor), is the largest positive integer that divides two or more numbers without leaving a remainder.

**For example**

We take 15 and 20 number.

The factors of 15 are 1, 3, 5, and 15.

The factors of 20 are 1, 2, 4, 5, 10, and 20.

The highest common factor (HCF) of 15 and 20 is 5, because it is the largest number that evenly divides both 15 and 20.

**LCM (Lowest Common Multiple)**:

LCM is the smallest positive integer that is evenly divisible by two or more numbers.

It represents the smallest common multiple shared by multiple numbers.

**For example**

We take 3 and 5 number.

Multiples of 3 are 3, 6, 9, 12, 15, 18, …

Multiples of 5 are 5, 10, 15, 20, 25, 30, ….

The LCM of 3 and 5 is 15, because it is the smallest common multiple.

## Example of HCF and LCM in Java

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | //HCF and LCM in Java import java.util.Scanner; public class HCFandLCMCal { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter first number: "); int n1 = scanner.nextInt(); System.out.print("Enter second number: "); int n2 = scanner.nextInt(); int hcf = calHCF(n1, n2); int lcm = calLCM(n1, n2); scanner.close(); System.out.println("HCF of " + n1 + " and " + n2 + " is: " + hcf); System.out.println("LCM of " + n1 + " and " + n2 + " is: " + lcm); } public static int calHCF(int n1, int n2) { while (n2 != 0) { int temp = n2; n2 = n1 % n2; n1 = temp; } return n1; } public static int calLCM(int n1, int n2) { int hcf = calHCF(n1, n2); return (n1 * n2) / hcf; } } |

**Output**

*C:\CodeRevise\java>javac HCFandLCMCal.java*

*C:\CodeRevise\java>java HCFandLCMCal*

*Enter first number: 3*

*Enter second number: 5*

*HCF of 3 and 5 is: 1*

*LCM of 3 and 5 is: 15*

*C:\CodeRevise\java>java HCFandLCMCal*

*Enter first number: 15*

*Enter second number: 20*

*HCF of 15 and 20 is: 5*

*LCM of 15 and 20 is: 60*

Check out our other Java Programming Examples