GCD or HCF of Two Numbers Java Program

The GCD (Greatest Common Divisor) of two numbers is the largest positive integer number that divides both the numbers without leaving any remainder. For example. GCD of 30 and 45 is 15. GCD also known as HCF (Highest Common Factor). 

import java.util.*;
class GCD
{
    public static void main(String[] args)
    {
        int a,b,gcd = 0;
        System.out.println("Enter two numbers : ");
        Scanner sc = new Scanner(System.in);
        a = sc.nextInt();
        b = sc.nextInt();
        int i;
        for(i = 1; i <= a && i <= b; i++)
        {
            if((a % i == 0) && (b % i == 0))
                gcd = i;
        }
        System.out.println("\nGCD of " + a + " and " + b + " is " + gcd);
        System.out.println();
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *