PHP - gmp_gcdext() 函式



定義和用法

gmp_gcdext() 函式計算給定數字的最大公約數 (GCD) 和乘數。

描述

gmp_gcdext() 有助於求解二元一次不定方程,例如:a*s + b*t = g = gcd(a,b)。它返回一個包含 g、s 和 t 值的陣列。

語法

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

引數

序號 引數 & 描述
1

a

可以是 GMP 資源數字、gmp 物件或數字字串。

2

b

可以是 GMP 資源數字、gmp 物件或數字字串。

返回值

PHP gmp_gcdext() 函式返回一個 GMP 數字陣列。

PHP 版本

此函式適用於 PHP 5.0.0 以上版本。

示例 1

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";
   }   
?>

這將產生以下結果 -

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

示例 2

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";
   }
?>

這將產生以下結果 -

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