Write a program to calculate HCF of Two given number


This program calculates the HCF of two numbers entered by the user using the Euclidean algorithm. The program first takes input from the user and stores them in dividend and divisor. It then loops until rem becomes 0, updating dividend and divisor at each iteration according to the Euclidean algorithm. Once the loop is finished, the HCF of the two numbers is stored in hcf and printed to the console.

  • Scanner input = new Scanner(System.in);: This creates a new Scanner object called input that reads user input from the console.
  • System.out.print("Enter the First Number :");: This displays the message "Enter the First Number :" on the console, prompting the user to enter an integer.
  • int dividend = input.nextInt();: This reads an integer value entered by the user using the Scanner object and assigns it to the variable dividend.
  • System.out.print("Enter the Second Number :"); : This displays the message "Enter the Second Number :" on the console, prompting the user to enter another integer.
  • int divisor = input.nextInt();: This reads an integer value entered by the user using the Scanner object and assigns it to the variable divisor.
  • int rem, hcf = 0; : This declares two integer variables rem and hcf. rem will store the remainder of the division operation between dividend and divisor, and hcf will hold the highest common factor of the two numbers.
  • do { ... } while(rem != 0); : This is a do-while loop that will run until rem becomes 0. Inside the loop, we perform the Euclidean algorithm to find the HCF of the two numbers.
  • rem = dividend % divisor; : This calculates the remainder of the division operation between dividend and divisor and stores it in the variable rem.
  • if(rem == 0) { hcf = divisor; }: If rem is 0, it means that divisor is the HCF of the two numbers, so we assign it to hcf.
  • else { dividend = divisor; divisor = rem; }: If rem is not 0, we update dividend to be divisor and divisor to be rem. This is because the HCF of two numbers is the same as the HCF of the smaller number and the remainder when the larger number is divided by the smaller number.
  • System.out.println("HCF : " + hcf);: Finally, we print the value of hcf which is the HCF of the two numbers entered by the user.

Source Code

import java.util.Scanner;
class Calculate_HCF
{
    public static void main(String[] args)
    {
		Scanner input = new Scanner(System.in);
 
		System.out.print("Enter the First Number :");
		int dividend = input.nextInt();        
		System.out.print("Enter the Second Number :");
		int divisor = input.nextInt();
		int rem, hcf = 0;
		do
		{
			rem = dividend % divisor;
 
			if(rem == 0)
			{
				hcf = divisor;
			}
			else
			{
				dividend = divisor;
				divisor = rem;
			}
 
		}while(rem != 0);
 
		System.out.println("HCF : " + hcf);
    }  
}

Output

Enter the First Number :3
Enter the Second Number :35
HCF : 1

Example Programs