The method used in C to find the greatest common divisor and the least common multiple of two Numbers

  • 2020-05-09 19:00:46
  • OfStack

Find the greatest common divisor of two positive integers,  

Idea: this is a very basic problem. The two most common ones are division and subtraction. The general formula is f(x, y) = f(y, x%y), f(x, y) = f(y, x-y) (x) > =y > 0). It's not hard to write out the algorithm based on the general formula, so I'm not going to do it here. The algorithm on programming beauty is given here, mainly to reduce the number of iterations.
        for x and y, if y = k * y1, x= k * x1, then f(x, y) = k * f(x1, y1). Also, if x = p * x1, assume that p is prime and y % p! = 0, then f(x, y) = f(p * x1, y) = f(x1, y). Let's say p is equal to 2.

Reference code:


// The functionality :  Find the greatest common divisor  
// Function parameters : x,y For the two Numbers  
// The return value :   The greatest common divisor  
int gcd_solution1(int x, int y) 
{ 
  if(y == 0) 
    return x; 
  else if(x < y) 
    return gcd_solution1(y, x); 
  else 
  { 
    if(x&1) //x Is odd  
    { 
      if(y&1) //y Is odd  
        return gcd_solution1(y, x-y); 
      else  //y Is an even number  
        return gcd_solution1(x, y>>1); 
    } 
    else //x Is an even number  
    { 
      if(y&1) //y Is odd  
        return gcd_solution1(x>>1, y); 
      else  //y Is an even number  
        return gcd_solution1(x>>1, y>>1) << 1; 
    } 
  } 
} 

Find the least common multiple:
The most common is the division between two integers, a and b:
a%b has a remainder of c
If c=0, b is the largest common divisor of the two Numbers
If c≠0, then a=b, b=c, and then go back to

The following non-recursive version:


int gcd_solution2(int x, int y) 
{ 
  int result = 1; 
  while(y) 
  { 
    int t = x; 
    if(x&1) 
    { 
      if(y&1) 
      { 
        x = y; 
        y = t % y; 
      } 
      else 
        y >>= 1; 
    } 
    else 
    { 
      if(y&1) 
        x >>= 1; 
      else 
      { 
        x >>= 1; 
        y >>= 1; 
        result <<= 1; 
      } 
    } 
  } 
  return result * x; 
} 


Related articles: