Q. Java Program to Find Gcd of Two Numbers.

Here you will find an algorithm and program in Java programming language to find GCD of two numbers. First let us understand what is GCD.

Explanation : GCD stands for Greatest Common Divisor, GCD of two numbers is the largest number that can exactly divide both numbers. It is also called as HCF.

For Example : GCD of 60 and 45 is 15. 15 is the greatest number which can divide both 60 and 45. Therefore GCD of 60 and 45 is 15.

Algorithm to find GCD of two numbers

START
1. Input 2 Numbers A and B and declare variable GCD which holds the result.
2. Run Loop i from 1 to i <= A and i <=B
    Check if A & B are completely divisible by i or not if yes then
         Assign GCD = i
    Loop End
3. Output GCD 
STOP


Java Program to Find Gcd of Two Numbers

public class LFC
{
  public static void main(String args[])
  {
  int num1 = 60, num2 = 45;
  int gcd;
  for (int i = 1; i < num1 && i < num2; i++) {
        if (num1 % i == 0 && num2 % i == 0)
          gcd = i;
      }
  System.out.println("GCD of " + num1 +" and " + num2 + " is " + gcd);
  }
}

Output

GCD of 60 and 45 is 15