卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章16333本站已运行3317

PHP程序计算一个数的阶乘中末尾零的个数

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 multiplying that number 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的因子,程序可以准确确定尾随零的数量。该代码为计算阶乘中尾随零提供了方便和高效的解决方案,有助于各种数学和编程应用。

卓越飞翔博客
上一篇: 如何使用C++编写高级嵌入式系统的各类功能
下一篇: 如何使用C++实现嵌入式系统的各类通信功能
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏