How to useLogarithms in Javascript
In this approach, we are Counting trailing zeroes by iteratively dividing the number by powers of 5. Accumulate quotients for total trailing zeroes in the factorial.
Syntax:
function trailingZeroes(n) {
let count = 0;
for (let i = 5; n / i >= 1; i *= 5) {
count += Math.floor(n / i);
}
return count;
};
Example: In this example, we are using Logarithms to find trailing zeroes of 25, in which 25! = 15511210043330985984000000. so here are 6 trailing zeroes.
function trailingZeroes(n) {
let count = 0;
for (let i = 5; n / i >= 1; i *= 5) {
count += Math.floor(n / i);
}
return count;
}
const num = 25;
const result = trailingZeroes(num);
console.log(`Trailing zeroes in ${num}! = ${result}`);
Output
Trailing zeroes in 25! = 6
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.
Contact Us