PHP 7.4.12 Released!


(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_gcdextCalculate GCD and multipliers


gmp_gcdext ( GMP $a , GMP $b ) : array

Calculates g, s, and t, such that a*s + b*t = g = gcd(a,b), where gcd is the greatest common divisor. Returns an array with respective elements g, s and t.

This function can be used to solve linear Diophantine equations in two variables. These are equations that allow only integer solutions and have the form: a*x + b*y = c. For more information, go to the » "Diophantine Equation" page at MathWorld



PHP 5.5 之前为 GMP 数值资源,PHP 5.6 之后为 GMP 对象或数字,或可以转为数字的字符串。


PHP 5.5 之前为 GMP 数值资源,PHP 5.6 之后为 GMP 对象或数字,或可以转为数字的字符串。


An array of GMP numbers.


Example #1 Solving a linear Diophantine equation

// Solve the equation a*s + b*t = g
// where a = 12, b = 21, g = gcd(12, 21) = 3
$a gmp_init(12);
$b gmp_init(21);
$g gmp_gcd($a$b);
$r gmp_gcdext($a$b);

$check_gcd = (gmp_strval($g) == gmp_strval($r['g']));
$eq_res gmp_add(gmp_mul($a$r['s']), gmp_mul($b$r['t']));
$check_res = (gmp_strval($g) == gmp_strval($eq_res));

if (
$check_gcd && $check_res) {
$fmt "Solution: %d*%d + %d*%d = %d\n";
printf($fmtgmp_strval($a), gmp_strval($r['s']), gmp_strval($b),
gmp_strval($r['t']), gmp_strval($r['g']));
} else {
"Error while solving the equation\n";

// output: Solution: 12*2 + 21*-1 = 3

add a note add a note

User Contributed Notes 1 note

17 years ago
The extended GCD can be used to calculate mutual modular inverses of two
coprime numbers. Internally gmp_invert uses this extended GCD routine,
but effectively throws away one of the inverses.

If gcd(a,b)=1, then r.a+s.b=1
Therefore  r.a == 1 (mod s) and s.b == 1 (mod r)
Note that one of r and s will be negative, and so you'll want to
canonicalise it.
To Top