How to useRecursive division in Javascript
In this approach, we Recursively divide the number by 5, adding quotients. Repeat until the number becomes 0. The sum of quotients gives trailing zeroes in factorial.
Syntax:
function trailingZeroes(n) {
if (n === 0) return 0;
return Math.floor(n / 5) + trailingZeroes(Math.floor(n / 5));
};
Example: In this example, we are using the recursive method to find trailing zeroes of 15.
function trailingZeroes(n) {
if (n === 0) return 0;
return Math.floor(n / 5) + trailingZeroes(Math.floor(n / 5));
}
let num = 15;
let result = trailingZeroes(num);
console.log(`Trailing zeroes in ${num}! = ${result}`);
Output
Trailing zeroes in 15! = 3
JavaScript Program to Count Trailing Zeroes in Factorial of a Number
In this article, we are going to learn how to count trailing zeroes in the factorial of a number in JavaScript. Counting trailing zeroes in the factorial of a number means determining how many consecutive zeros appear at the end of the factorial’s decimal representation. It’s a measure of how many times the factorial value is divisible by 10.
Example:
Input : n = 5
Factorital of 5 i.e. 5! = 5 * 4 * 3 * 2 * 1 = 120
Output : 1
Here we have one trailing 0.
Input : n = 15.
Factorial of 15 i.e. 15! = 15 * 14 * 13 * 12 * 11 ... 3 * 2 * 1 = 1307674368000
Output : 3
Here we have 3 trailing 0.
There are several methods that can be used to Count trailing zeroes in the factorial of a number in JavaScript, which are listed below:
Table of Content
- Approach 1: Using Division method
- Approach 2: Using Recursive division
- Approach 3: Using Logarithms
- Approach 4: Using Prime Factorization
We will explore all the above methods along with their basic implementation with the help of examples.