Skip to main content

GCD Function


The greatest common divisor (GCD) is a fundamental concept in number theory, and its computation plays a crucial role in various mathematical and computational applications. In this comprehensive article, we will delve into the GCD function, exploring both recursive and non-recursive approaches, with a focus on Euclid’s division as an efficient method for GCD calculation.

Recursive Approach:

// A function to calculate the greatest common divisor of two positive integers
int gcd(int a, int b){
  // If one of the numbers is zero, the other is the GCD
  if(a == 0) return b;
  if(b == 0) return a;

  // Use Euclid's algorithm to find the GCD recursively
  // The GCD of a and b is the same as the GCD of b and the remainder of a/b
  return gcd(b, a % b);
}

Non-Recursive Approach:

// A non-recursive function to find the gcd of two positive integers
int gcd(int a, int b) {
  // Assume that a and b are positive
  // If not, convert them to positive by taking their absolute values
  if (a < 0) a = -a;
  if (b < 0) b = -b;

  // If one of them is zero, return the other as the gcd
  if (a == 0) return b;
  if (b == 0) return a;

  // Use a while loop to keep dividing the larger number by the smaller number
  // and take the remainder as the new smaller number
  while (b != 0) {
    int temp = b; // Store the smaller number in a temporary variable
    b = a % b;    // Update the smaller number as the remainder of the division
    a = temp;     // Update the larger number as the previous smaller number
  }

  // When the loop ends, b is zero and a is the gcd
  return a;
}

Euclid’s Division:

Euclid’s division is an efficient algorithm for finding the GCD of two positive integers. It follows these steps:

  1. Let a and b be the two numbers, where a is larger than b.
  2. Divide a by b and get the remainder r.
  3. If r is zero, then b is the GCD.
  4. If r is not zero, replace a by b and b by r, and repeat the previous step until r becomes zero.

Example:

Suppose we want to find the GCD of 56 and 12:

  1. (56 / 12 = 4) with remainder (8)
  2. (12 / 8 = 1) with remainder (4)
  3. (8 / 4 = 2) with remainder (0)

Conclusion:
Euclid’s division is based on the idea that the GCD of two numbers remains unchanged if we subtract the smaller number from the larger one. Understanding and implementing the GCD function with Euclid’s division is essential for various applications in computer science, mathematics, and beyond.

For more in-depth information on Euclid’s division and its applications, you can refer to sources such as Euclidean algorithm - Wikipedia and Euclidian Algorithm: GCD (Greatest Common Divisor) Explained with C++ and Java Examples.

Comments