Write a program to output the number of consecutive trailing zeros in the factorial of a number?
Solution:
1. The number of trailing zeros in a number is equivalent to the power of 10 in the factor of that number.
2. The number power of 10 in the factors is the same as the minimum of the power of 2 and power of 5 in the factors.
3. In any factorial there will be many more powers of 2 than the powers of 5.
Hence all we need to do is count the power of 5 in the factorial.
4. Count all the multiples of 5, they all add one power of 5. Then count all the multiples of 25, they all add an extra power of 5. Notice how 25 added two powers of 5, so I can put that as, one power because it’s a multiple of 5 and one extra power because it’s a multiple of 25. Then count all the multiple of 125 (5^3) in the factorial multiplication, they add another extra power of 5… and so on.
Implementation
public static int findTrailingZeros(int n) { int cnt = 0, temp = 5; if(n< 0){ System.out.println("Error: There is no Factorial for a number less than 0"); return -1; //error condition } while(temp < n) { cnt += n / temp; temp *= 5; } return cnt; }
Correct answer is while(n> 0)
{cnt+=n/temp
n=n/temp}
rename the argument ‘number’ to ‘n’.
Thanks for your comment. We have corrected it.
Hi,
This is not working for n = 25. The factorial has 6 trailing zeros. But the output of this function gives 5.
Thanks,
Vithal
public static int findTrailingZeros(int n)
02
{
03
int cnt = 0, temp = 5;
04
if(n< 0){
05
System.out.println("Error: There is no Factorial for a number less than 0");
06
return -1; //error condition
07
}
08
09
while(temp < =n)
10
{
11
cnt += n / temp;
12
temp *= 5;
13
}
14
return cnt;
15
}