Thursday, May 30, 2013

Program to find GCD of two numbers

In mathematics, the greatest common divisor (gcd), also known as the greatest common factor (gcf), or highest common factor (hcf), of two or more integers (at least one of which is not zero), is the largest positive integer that divides the numbers without a remainder - from Wikipedia
For example, the GCD of 8 and 12 is 4
Euclidian method: This is also called division algorithm. Take smallest of the two numbers and divide the other number. If the remainder is zero smaller number is the GCD. Otherwise replace the smaller number with remainder, and bigger number with present smaller number and repeat the same procedure.

Here is the step-by-step calculation


8)12(1
   8
 ----
   4)8(2
     8
    ---
     0


The following c++ code implements the iterative and recursive version of Euclidian algorithm.



#include <iostream>

using namespace std;
void swap(int &x, int &y)
{
 int temp = x;
 x = y;
 y = temp;
}
//iterative version of Euclidian algorithm
int gcd(int x,int y)
{
 while ( (y % x) != 0)
 {
  int r = y % x;
  y = x;
  x = r;
 }
 return x;
}
//recursive version of Euclidian algorithm
int gcd_recursive(int x, int y)
{
 if( y % x == 0)
  return x;
 return gcd_recursive( y%x, x);
}

int main()
{
 int x,y;
 //read two numbers
 cin>>x>>y;
 //both iterative and recursive versions requires first parameter <= second
 //swap if firt is greater
 if( x > y )
 {
  swap(x,y);
 } 
 cout<<"GCD(" << x << "," << y << ")=" << gcd_recursive(x,y) << endl;
 return 0;
}