2014-02-22 57 views
2

如何使用PHP/GMP計算整數的第n個根?使用PHP/GMP計算整數的第n個根

雖然我在PHP source發現了一個叫gmp_root(a, nth)功能,似乎這個功能尚未發佈任何版本尚未*:http://3v4l.org/8FjU7

*)5.6.0alpha2處於寫作的時候最新的一個

+1

** + 1個**爲知識庫共享(Q&A)。 –

+0

1)請說清楚你說的是整數。 2)您對PHP源代碼的評論不清楚,它似乎在您的鏈接中實現。你的意思是代碼還沒有包含在發行版中嗎? 3)在問題中明確說明,而不僅僅是標籤,你想在PHP中計算根。從你的問題的標題,答案是'mpz_root'。你很高興分享你的想法,但你需要花時間正確地寫下問題,否則答案將被浪費。 –

+0

@MarcGlisse感謝您的評論。你說得對,我沒有花足夠的時間。我希望現在編輯後的問題和答案更好。隨意做進一步的言論或自己編輯帖子;) – ComFreek

回答

3

原始來源:Calculating Nth root with bcmath in PHP –感謝和信用到HamZa

我已經重寫的代碼來使用GMP代替bcmath時的:

function gmp_nth_root($num, $n) { 
    if ($n < 1) return 0; // we want positive exponents 
    if ($num <= 0) return 0; // we want positive numbers 
    if ($num < 2) return 1; // n-th root of 1 or 2 give 1 

    // g is our guess number 
    $g = 2; 

    // while (g^n < num) g=g*2 
    while (gmp_cmp(gmp_pow($g, $n), $num) < 0) { 
     $g = gmp_mul($g, 2); 
    } 
    // if (g^n==num) num is a power of 2, we're lucky, end of job 
    if (gmp_cmp(gmp_pow($g, $n), $num) == 0) { 
     return $g; 
    } 

    // if we're here num wasn't a power of 2 :( 
    $og = $g; // og means original guess and here is our upper bound 
    $g = gmp_div($g, 2); // g is set to be our lower bound 
    $step = gmp_div(gmp_sub($og, $g), 2); // step is the half of upper bound - lower bound 
    $g = gmp_add($g, $step); // we start at lower bound + step , basically in the middle of our interval 

    // while step != 1 

    while (gmp_cmp($step, 1) > 0) { 
     $guess = gmp_pow($g, $n); 
     $step = gmp_div($step, 2); 
     $comp = gmp_cmp($guess, $num); // compare our guess with real number 
     if ($comp < 0) { // if guess is lower we add the new step 
      $g = gmp_add($g, $step); 
     } else if ($comp == 1) { // if guess is higher we sub the new step 
      $g = gmp_sub($g, $step); 
     } else { // if guess is exactly the num we're done, we return the value 
      return $g; 
     } 
    } 

    // whatever happened, g is the closest guess we can make so return it 
    return $g; 
}