Friday, October 11, 2013

finding the greatest common divisor of 2 numbers in O(logn).Euclid's algorithm

We usually find the greatest common divisor of 2 number in this way. We find the prime factorization of two numbers.
a=p1^a1*p2^a2*....*pn^an
b=q1^b1*q2^b2*...*qn^bn
And we choose common prime factors and multiply them to find the greatest common divisor. There is a better approach to this problem.
   We will call the function of finding the greatest common divisor GCD(a,b).
   Euclid's algorithm suggests that GCD(a,b)=GCD(a%b,b) (When a is greater than b)
   Here is the code for finding GCD(a,b);
    int GCD(int a,int b)   // we consider that a is greater than b from the beginning
    {
          while(b>0)
          {
                a=a%b;
                swap(a,b);/// because we considered that a is always greater than b and it is clear that a%b<b)
          }
          return a;
     }

          

No comments:

Post a Comment