PHP程式計算一個數的階乘中末尾零的個數

WBOY
發布: 2023-08-26 17:18:01
轉載
733 人瀏覽過

PHP程式計算一個數的階乘中末尾零的個數

階乘是什麼?

The factorial of a non-negative integer, denoted by the symbol "!", is the product of all positive integers less than or equal to that number. In other words, the factorial of a number is obtained by multiply by all the positive integers below it.

For example, the factorial of 5 is calculated as:

5! = 5 x 4 x 3 x 2 x 1 = 120

同樣地,0的階乘被定義為1:

0! = 1

Factorials are often used in mathematics and combinatorics to count permutations, combinations, and arrangements of objects. They also have applications in probability, calculus, and various other areas of mathematics.

PHP Program to Count Trailing Zeroes in Factorial of a Number

在一個數的階乘中,尾隨零指的是階乘的十進位表示中連續零的個數。

例如 10! = 10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1

執行乘法運算

10! = 3,628,800

The factorial of 10 is 3,628,800.

Trailing zeroes in factorial of 10 are 2 because the number of consecutive zeros at the end of the factorial.

Example

<?php

function countTrailingZeroes($number) {
   $count = 0;

   // Divide the number by powers of 5 and count the quotient
   // The quotient represents the number of trailing zeroes
   while ($number >= 5) {
      $number = (int) ($number / 5);
      $count += $number;
   }

   return $count;
}

// Test the function
$number = 20;
$trailingZeroes = countTrailingZeroes($number);
echo "The factorial of $number has $trailingZeroes trailing zeroes.<br>";

// Test the function
$number = 14;
$trailingZeroes = countTrailingZeroes($number);
echo "The factorial of $number has $trailingZeroes trailing zeroes.";
?> 
登入後複製

Output

#
The factorial of 20 has 4 trailing zeroes.
The factorial of 14 has 2 trailing zeroes.
登入後複製

程式碼解釋

在範例程式碼中呼叫了一個名為countTrailingZeroes的PHP函數。此函數計算給定數字的階乘中尾部零的個數。它是透過將數字除以5的冪併計算商來實現。只要數字大於或等於5,while迴圈就會繼續執行。在循環內部,使用整數除法將數字除以5,以計算目前數字中因子5的數量。將得到的商加到一個名為$count的變數中,該變數用於追蹤尾部零的個數。循環結束後,從函數中返回最終的計數值。

在該函數下方,有一個測試案例,其中使用值為123呼叫了該函數。這個測試案例使用countTrailingZeroes函數計算了20的階乘中尾隨零的數量。結果儲存在一個名為$trailingZeroes的變數中。最後,使用echo顯示結果,提供輸入數字和其階乘中尾隨零的數量

在這種情況下,20的階乘是2,432,902,008,176,640,000,所以它的階乘末端有4個零,而14的階乘是87,178,291,200。所以它的階乘末端有2個零。

Conclusion

提供的PHP程式有效地計算給定數字的階乘中尾隨零的數量。它利用while循環將數字除以5的冪併計算商,表示尾隨零的數量。透過利用這種方法,程式避免了計算整個階乘的需要。這種技術是有效的,因為階乘中的尾隨零​​來自因子5。因此,透過計算5的因子,程式可以準確地確定尾隨零的數量。此程式碼為計算階乘中尾隨零提供了方便和高效的解決方案,有助於各種數學和程式應用。

以上是PHP程式計算一個數的階乘中末尾零的個數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!