gmp_gcdext

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

gmp_gcdextCalcula el máximo común divisor y multiplicadores

Descripción

gmp_gcdext(GMP|int|string $num1, GMP|int|string $num2): array

Calcula g, s, y t, tal que a*s + b*t = g = gcd(a,b), donde gcd es el máximo común divisor. Devuelve un arreglo con los elementos respectivos g, s y t.

Ésta función puede ser usada para resolver ecuaciones de diofántica lineal equations en dos variables. Estas son ecuaciones que permiten solo soluciones enteras y tienen la forma: a*x + b*y = c. Para más información, vaya a » "Diophantine Equation" en la página MathWorld

Parámetros

num1

resource de número de GMP en PHP 5.5 y anterior, o un objeto de GMP en PHP 5.6 y posterior, o un string numérico siempre que sea posible convertirlo a un número.

num2

resource de número de GMP en PHP 5.5 y anterior, o un objeto de GMP en PHP 5.6 y posterior, o un string numérico siempre que sea posible convertirlo a un número.

Valores devueltos

Un array de números GMP.

Ejemplos

Ejemplo #1 Resolver ecuaciones de diofántica lineal

<?php
// Resolver la ecuación a*s + b*t = g
// donde 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($fmt, gmp_strval($a), gmp_strval($r['s']), gmp_strval($b),
gmp_strval($r['t']), gmp_strval($r['g']));
} else {
echo
"Error mientras se resolvia la ecuación\n";
}

// output: Solución: 12*2 + 21*-1 = 3
?>

add a note add a note

User Contributed Notes 1 note

up
0
FatPhil
20 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