Skip to main content

gcd

pub fn gcd(a: i128, b: i128) -> i128
Expand description

Computes the greatest common divisor (GCD) of two integers using the classical Euclidean algorithm.

§Overview

The greatest common divisor of two integers is the largest positive integer that divides both numbers without leaving a remainder. This implementation uses the Euclidean algorithm, based on

gcd(a, b) = gcd(b, a mod b)

repeated until the second operand becomes zero; the first operand is then the GCD up to sign, and its absolute value is returned.

§Properties

  • Time Complexity: O(log(min(|a|, |b|)))
  • Space Complexity: O(1)

§Edge Cases

  • The result is never negative: gcd(4, -6) = 2.
  • If one of the inputs is zero, the function returns the absolute value of the other.
  • If both inputs are zero, the function returns zero (a common convention).
  • i128::MIN with zero (or with itself) has no representable GCD and overflows.