How to usePrime Factorization in Javascript
In this approach, we find the prime factorization of the given number, n. Since trailing zeroes in a factorial result from pairs of 2s and 5s, and 2s occur more frequently than 5s in the prime factorization of integers, we count the occurrences of 5s to determine the number of trailing zeroes.
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 will use prime factorization to find trailing zeroes of 30.
function trailingZeroes(n) {
let count = 0;
for (let i = 5; n / i >= 1; i *= 5) {
count += Math.floor(n / i);
}
return count;
}
const num = 30;
const result = trailingZeroes(num);
console.log(`Trailing zeroes in ${num}! = ${result}`);
Output
Trailing zeroes in 30! = 7
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.