Java Program to Find GCD of Numbers

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 60 and 75 is 15. GCD also known as HCF (Highest Common Factor). In this tutorial we will write couple of different Java programs to find out the GCD of two numbers.

Example 1: Java Program to find GCD of three numbers using for loop

In this example, we are finding the GCD of three given numbers using for loop.

We are running a for loop from 1 to the smaller number and inside loop we are dividing both the numbers with the loop counter “i” which ranges from 1 to the smaller number value. If the value of i divides both numbers with no remainder then we are assigning that value to the variable “GCD”. At the end of the loop, the variable “GCD” will have the largest number that divides both the numbers without remainder.

public class Main{
     public static void main(String[] args) {
          int var1 = 84, var2 = 90, var3=120 ,gcd = 1;
          for(int i = 1; i <= var1 && i <= var2 && i <= var3; i++){
             if(var1%i==0 && var2%i==0 && var3%i==0)
                gcd = i;
          }
          System.out.printf("GCD of %d and %d and %d is: %d", var1, var2, var3, gcd);
     }
}

Output:

GCD of 84 and 90 and 120 is: 6

Similar way you can find GCD of two numbers as well.

Reference:

%d bloggers like this: