Java Programs

H.C.F. or G.C.D. Of Two Number Program in Java

In this tutorial, we are going to learn writing java program to calculate the Highest Common Factor of two numbers. Our program will take two numbers as the inputs given by the user and returns the h.c.f. of given numbers.

For example, for the inputs of the two numbers 4 and 6. Our program will return ‘2’ as an output.

Java Program to calculate HCF/GCD of two Numbers

import java.util.*;

public class Main {
	
    public static void main(String[] args) {
    	
        double num1,num2,gcd=0;
        System.out.println("Java Program to calculate HCF/GCD " );
        Scanner sc = new Scanner(System.in);
        System.out.println("Please give first number");
        num1= sc.nextDouble();
        System.out.println("Please give second number");
        num2= sc.nextDouble();
        
        for(int i=1; i <= num1 && i <= num2; ++i)
        {
            if(num1%i==0 && num2%i==0)
            gcd = i;
        }
        System.out.println("G.C.D of number "+num1+" and "+num2+" = " +gcd);
    }
}

Output

Java Program to calculate HCF/GCD 
Please give first number
6
Please give second number
2
G.C.D of number 6.0 and 2.0 = 2.0

Explanations

For inputs 6 and 2, the program is finding the highest factor that is common in both 6 and 2.
The factor of 6 is 1,2,3 and the factor of 2 is 1,2. The highest factor common in
both is 2.

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs