gcd function

num gcd(
  1. List<num> numbers
)

Returns the greatest common divisor of a list of numbers.

This function uses the Euclidean algorithm to compute the GCD.

Parameters:

  • numbers: A list of numbers for which the GCD is computed.

Returns:

  • An number representing the GCD of the provided numbers.

Example:

print(gcd([48, 18, 24]));  // Output: 6

Implementation

num gcd(List<num> numbers) {
  if (numbers.isEmpty) {
    throw ArgumentError('List of numbers cannot be empty.');
  }

  // Sort and ensure all numbers are positive
  numbers = numbers.map((x) => x.abs()).toList()..sort();

  num a = numbers.removeAt(0);

  for (var b in numbers) {
    while (true) {
      a %= b;
      if (a == 0) {
        a = b;
        break;
      }
      b %= a;
      if (b == 0) break;
    }
  }

  return a;
}