The factorial of an integer is the product of all positive integers from to . A zero at the end of the product appears as a result of multiplying and . However, in the prime factorization of there are more twos than fives. Therefore, the number of zeros at the end of is equal to the number of fives in the factorization of . The number of such fives is
The summation continues until the next term equals .
Example
Find the number of zeros at the end of
The third term is already equal to zero, since 100 < 5^3 = 125.
Algorithm implementation
Read the value of .
scanf("%d",&n); Compute the result using the formula.
res = 0;
while(n > 0)
{
n /= 5;
res += n;
}Print the number of zeros at the end of
printf("%d\n",res);Java implementation
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
int n = con.nextInt();
int res = 0;
while (n > 0)
{
n /= 5;
res += n;
}
System.out.println(res);
con.close();
}
} Python implementation
Read the value of .
n = int(input())Compute the result using the formula.
res = 0
while n > 0:
n = n // 5
res += nPrint the number of zeros at the end of
print(res)