Skip to content

Core\Math::gcd

Finds the greatest common divisor of two whole numbers. This is the largest number that divides both of them with no remainder. For 12 and 18, the result is 6.

The signs of the two numbers do not change the result, and the result is never negative. When one number is 0, the result is the other number without its sign. When both are 0, the result is 0. The positive value of Core\Math::INT_MIN is too big for an int, so a call whose result would be that value throws an ArithmeticError.

Use it to write a fraction or a ratio with the smallest numbers. Core\Math::lcm finds the smallest number that both numbers divide.

The examples below show a few pairs of numbers, then zero and negative numbers, then how to write the size of an image as a short ratio, such as 16:9.

Parameters

  • $aintThe first integer. Its sign does not change the result.
  • $bintThe second integer. Its sign does not change the result.

Return value

Returns int. The greatest common divisor, which is never negative. When one integer is 0, the result is the other one without its sign. When both are 0, the result is 0.

Errors

  • ArithmeticErrorWhen the result does not fit an int. This happens only when one integer is Core\Math::INT_MIN and the other is Core\Math::INT_MIN or 0.

Examples

A few pairs

<?nvs
// Shows the greatest common divisor of a few pairs of numbers.
// 6 is the largest number that divides both 12 and 18. This prints 6.
echo Core\Math::gcd(12, 18), "\n";
// 7 divides 49, so 7 is the result. This prints 7.
echo Core\Math::gcd(7, 49), "\n";
// 17 and 5 have no common divisor except 1. This prints 1.
echo Core\Math::gcd(17, 5), "\n";
Output
6
7
1

Zero and negative numbers

<?nvs
// Shows the result when one of the numbers is zero or negative.
// Every number divides 0, so the result is the other number. This prints 8.
echo Core\Math::gcd(8, 0), "\n";
// When both numbers are 0, the result is 0.
echo Core\Math::gcd(0, 0), "\n";
// The signs do not change the result, and it is never negative. This prints 4.
echo Core\Math::gcd(-8, -12), "\n";
Output
8
0
4

Image aspect ratio

<?nvs
// Shows how to write the width and height of an image as a short ratio, such as 16:9.
class AspectRatio
{
// Both sides are divided by their greatest common divisor.
// The result has the same shape, written with the smallest whole numbers.
public static function of(int $width, int $height): string
{
int $divisor = Core\Math::gcd($width, $height);
string $across = Core\Math::quotient($width, $divisor) as string;
string $down = Core\Math::quotient($height, $divisor) as string;
return $across . ':' . $down;
}
}
// This prints 16:9.
echo AspectRatio::of(1920, 1080), "\n";
// This prints 4:3.
echo AspectRatio::of(1024, 768), "\n";
// A square image. This prints 1:1.
echo AspectRatio::of(1080, 1080), "\n";
Output
16:9
4:3
1:1