• PHP Video Tutorials

PHP - gmp_gcdext() Function



Definition and Usage

The gmp_gcdext() function calculates the GCD and multipliers for the given numbers.

Description

gmp_gcdext() helps to solve linear Diophantine equations in two variables for example : a*s + b*t = g = gcd(a,b).It returns an array with values g, s and t.

Syntax

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

Parameters

Sr.No Parameter & Description
1

a

It can a GMP resource number , a gmp object or a numeric string.

2

b

It can a GMP resource number , a gmp object or a numeric string.

Return Values

PHP gmp_gcdext() function returns an array of GMP numbers.

PHP Version

This function will work from PHP Version greater than 5.0.0.

Example 1

Working of gmp_gcdext −

<?php
   // Solve the Diophantine  equation a*s + b*t = g = gcd(a,b)
   // where a = 18, b = 24, g = gcd(18, 24) = 6
   $a = gmp_init(18);
   $b = gmp_init(24);
   $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 = "The result of the equation is : %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";
   }   
?>

This will produce following result −

The result of the equation is : 18*-1 + 24*1 = 6

Example 2

Working of gmp_gcdext −

<?php
   // Solve the Diophantine  equation a*s + b*t = g = gcd(a,b)
   // where a = 24, b = 36, g = gcd(24, 36) = 12
   $a = gmp_init(24);
   $b = gmp_init(36);
   $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 = "The result of the equation is : %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";
   }
?>

This will produce following result −

The result of the equation is : 24*-1 + 36*1 = 12
php_function_reference.htm
Advertisements