Tuesday, July 10, 2012

Efficient java program to find GCD of given two numbers

The following java code finds the biggest common factor(GCD) for two numbers easily. Otherwise we need to check it from smallest number.Lets assume that the smallest number is n. So we need to check it from n,n-1....1 to find the common factor.But here out of two inputs set the biggest one to b. Then find the common factor using the % operator and keep changing the values of a and b until you find the common factor.

Code : (in JAVA)

 Sample input and output
1.Input
   8 5
  Output
   1
2.Input 
   26 4
  Output
   2

Please let me know if you have any questions .