Java Program to Find GCD of two Numbers

First of all, you should understand what is GCD?

GCD or also called HCF means Highest Common Factor or Greatest common divisor. GCD of two integers is the largest number which can divide both integers without any remainder.

Method: 1 Find GCD of two numbers using For loop and if else statement.

public class GCDOfTwoNumbers {

    public static void main(String[] args) {

        int n1 = 81, n2 = 153, gcd = 1;

        for(int i = 1; i <= n1 && i <= n2; ++i)
        {
            // Checks if i is a factor of both the integers
            if(n1 % i==0 && n2 % i==0)
                gcd = i;
        }

        System.out.printf("G.C.D of %d and %d is %d", n1, n2, gcd);
    }
}
Output
G.C.D of 81 and 153 is 9

Method: 2 HCF of two numbers using while loop and if-else statement

public class GDCOfTwoNumbers {

    public static void main(String[] args) {

        int n1 = 81, n2 = 153;

        while(n1 != n2)
        {
            if(n1 > n2)
                n1 -= n2;
            else
                n2 -= n1;
        }

        System.out.println("G.C.D = " + n1);
    }
}
Output
G.C.D = 9

Leave a Reply