How to useDivision method in Javascript
In this approach we are using repeated division by 5, sum quotients while n >= 5, counting trailing zeroes in factorials.
Syntax:
function trailingZeroes(n) {
let count = 0;
while (n >= 5) {
n = Math.floor(n / 5);
count += n;
}
return count;
};
Example: In this example, we are using a simple division method to find trailing zeroes of 5 and 15, in which 5! = 120 and 15! = 1307674368000.
function trailingZeroes(n) {
let count = 0;
while (n >= 5) {
n = Math.floor(n / 5);
count += n;
}
return count;
}
let num1 = 5;
let num2 = 15;
let result = trailingZeroes(num1);
let result2 = trailingZeroes(num2);
console.log(`Trailing zeroes in ${num1}! = ${result}`);
console.log(`Trailing zeroes in ${num2}! = ${result2}`);
Output
Trailing zeroes in 5! = 1 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.