Skip to content

Core\BigInt::gcd

Returns the greatest common divisor of this number and another one, as a new Core\BigInt.

The greatest common divisor is the largest number that divides both of them exactly. It is what you use to reduce a fraction or a ratio to its shortest form: divide both sides by it.

The result is never negative, and the sign of the two numbers does not change it. The order of the two numbers does not change it either. When one of them is zero the result is the other number, because every number divides zero exactly. Two zeroes give 0.

Good to know: Core\Math::gcd does the same for plain int values. Use Core\BigInt::gcd when a number may grow too large for an int.

Parameters

  • $otherCore\BigIntThe other value. If both values are 0, the result is 0.

Return value

Returns Core\BigInt. A non-negative BigInt.

Examples

The largest common divisor

<?nvs
// Shows the greatest common divisor of two numbers: the largest number that
// divides both of them exactly.
var $first = Core\BigInt::of(360);
var $second = Core\BigInt::of(48);
// `gcd` gives the largest number that divides 360 and 48. This prints 24.
echo $first->gcd($second), "\n";
// The sign of a number and the order of the two do not change the result.
// This prints 24 again.
echo $second->gcd($first->negated()), "\n";
Output
24
24

When one number is zero

<?nvs
// Shows what `gcd` gives when one of the two numbers is zero.
var $value = Core\BigInt::of(42);
var $zero = Core\BigInt::of(0);
// Every number divides zero exactly, so the result is the other number.
// This prints 42.
echo $value->gcd($zero), "\n";
// Two zeroes have no largest common divisor. The result is 0.
echo $zero->gcd($zero), "\n";
Output
42
0

Reducing a ratio to its shortest form

<?nvs
// Shows how to reduce a ratio to its shortest form. Both amounts are counted in
// the smallest unit of a currency, so they are far too large for an `int`.
var $paid = Core\BigInt::parse('12193263112482853185200427');
var $total = Core\BigInt::parse('1524157875171467887501905210');
// Dividing both amounts by their greatest common divisor gives the ratio in
// its shortest form. This prints 32921810703292181 / 4115226300411522630.
var $divisor = $paid->gcd($total);
echo $paid->dividedBy($divisor), ' / ', $total->dividedBy($divisor), "\n";
Output
32921810703292181 / 4115226300411522630