Problem : Given a number, can you find out how many trailing zeroes are there in the factorial of that number.
There is another solution to this problem where in we do not need to find the factorial of the given number in order to find the number of trailing zeroes. You can find more about this here -
This is an interesting problem. One solution to this problem is to find the factorial of the given number and then count the trailing zeroes. Here is the code for this -
/**
* This will find the number of trailing zeroes
* in the factorial of a number.
*
* @param n
* @return int
*/
public static int trailingZeroesInFactorial(int n)
{
BigInteger factorial = factorial(n);
String string = factorial.toString();
int trailingZeroCount = 0;
for (int i = string.length() - 1; i >= 0; i--)
{
if (string.charAt(i) == '0')
{
trailingZeroCount++;
}
else
{
break;
}
}
return trailingZeroCount;
}
There is another solution to this problem where in we do not need to find the factorial of the given number in order to find the number of trailing zeroes. You can find more about this here -
There is a formula to find the number of trailing zeroes in a factorial -
* k
* TrailingZeroes = summation [ Math.floor ( N / Math.pow(5, i) ) ]
* i = 1
*
where k must be chosen such that Math.pow(5, k+1) > N
Here is the code -
public static int trailingZeroes(int n)
{
int trailingZeroCount = 0;
int k = 0;
// Find a value k such that Math.pow(5, k+1) > n
for (int i = 0; i < n; i++)
{
if (Math.pow(5, i+1) > n)
{
k = i;
break;
}
}
for (int i = 1; i <= k; i++)
{
trailingZeroCount += Math.floor( (n * 1.0) / Math.pow(5, i));
}
return trailingZeroCount;
}
Comments