In this tutorial you will learn about the Java Program to Find HCF and LCM of Two Numbers and its application with practical example.
In this tutorial, we will learn to create a Java Program to Find HCF and LCM of Two Numbers using Java programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following Java programming topics:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
What is LCM Number.
LCM is a method to finding the smallest possible multiplication of two or more numbers. LCM of a numbers is divisible by both or more numbers. For example, LCM of 5 ,4 and 20 is 20.
What is HCF Number.
GCD(Greatest Common Divisor) or HCF (Highest Common Factor) . When we finding the factor of two numbers, Highest Common Factor of numbers is the Largest factor that divides these two numbers. The greatest factor found from the common factors is called the HCF. It is also called the Greatest common factor.
Java Program to Find HCF and LCM of Two Numbers.
In this program we would find HCF and LCM of given numbers .first of we would take a value sfrom user and find then we will find HCF and LCM of given numbers.
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 31 |
// java program to find HCF and LCM of given numbers. import java.util.Scanner; public class Hcd_Lcm { public static void main(String args[]) { // Decalring avriables and taking values from user. int t1, t2, no1, no2, temp, hcf, lcm; Scanner scanner = new Scanner(System.in); System.out.print("Enter First Number "); no1 = scanner.nextInt(); System.out.print("Enter Second Number "); no2 = scanner.nextInt(); scanner.close(); // pass number to temp variables.. t1 = no1; t2 = no2; // checking condtrion for lc and Hcf.. while(t2 != 0){ temp = t2; t2 = t1%t2; t1 = temp; } hcf = t1; lcm = (no1*no2)/hcf; // Printing the result.. System.out.println("HCF of input numbers: "+hcf); System.out.println("LCM of input numbers: "+lcm); } } |
Output
Hcf and Lcm
In the above program, we have first declared and initialized a set variables required in the program.
- no1,no2= it will hold entered numbers.
- t1and t2= it will hold temp values.
- lcm = it will hold result of lcm
- Hcf = it will hold result of hcf.
After that we take a numbers from user and find HCF and LCM of given numbers.
after that we calculate hcf and lcm of given number as shown in image below
And finally we will print both hcd and lcm of given numbers.