Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP Program to Count Trailing Zeroes in Factorial of a Number
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
Similarly, the factorial of 0 is defined to be 1:
0! = 1
What are Trailing Zeroes?
In the factorial of a number, trailing zeroes refer to the number of consecutive zeros at the end of the factorial's decimal representation.
For example 10! = 10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1
Performing the multiplication ?
10! = 3,628,800
The factorial of 10 is 3,628,800.
Trailing zeroes in factorial of 10 are 2 because there are 2 consecutive zeros at the end of the factorial.
Algorithm
To count trailing zeroes efficiently without calculating the entire factorial, we use the fact that trailing zeroes are produced by factors of 10, which come from pairs of factors 2 and 5. Since there are always more factors of 2 than 5 in a factorial, we only need to count the factors of 5 ?
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 with another number
$number = 14;
$trailingZeroes = countTrailingZeroes($number);
echo "The factorial of $number has $trailingZeroes trailing zeroes.<br>";
// Test with 10 for verification
$number = 10;
$trailingZeroes = countTrailingZeroes($number);
echo "The factorial of $number has $trailingZeroes trailing zeroes.";
?>
The factorial of 20 has 4 trailing zeroes. The factorial of 14 has 2 trailing zeroes. The factorial of 10 has 2 trailing zeroes.
How It Works
The algorithm works by repeatedly dividing the number by 5 and adding the quotient to our count:
| Step | For n=20 | Calculation | Count |
|---|---|---|---|
| 1 | 20 ÷ 5 | 4 | 4 |
| 2 | 4 ÷ 5 | 0 | 4 + 0 = 4 |
This counts factors of 5, 25 (5²), 125 (5³), and so on. Each power of 5 contributes additional trailing zeroes.
Conclusion
The provided PHP program efficiently calculates trailing zeroes in factorials without computing the entire factorial. By counting factors of 5 using division, it provides an optimal solution for this mathematical problem.
