gcd static method

int gcd(
  1. int a,
  2. int b
)

Calculates the Greatest Common Divisor (GCD) of two integers a and b using the Euclidean algorithm.

The GCD is the largest positive integer that divides both a and b without leaving a remainder.

The algorithm handles negative inputs by taking their absolute values, as GCD is conventionally defined for positive integers.

Parameters:

  • a: The first integer.
  • b: The second integer.

Returns: An int representing the Greatest Common Divisor of a and b. Returns the absolute value of a if b is 0, and the absolute value of b if a is 0. If both are 0, it returns 0.

Implementation

static int gcd(int a, int b) {
  a = a.abs();
  b = b.abs();

  while (b != 0) {
    var temp = b;
    b = a % b;
    a = temp;
  }

  return a;
}