Thursday, April 29, 2010

Trailing Zeros of a Factorial

    0 /*
1 * Problem: To find the number of trailing zeros in a factorial (n)
2 * URL: http://www.codechef.com/problems/FCTRL/
3 * Input: n
4 * Output: No. of Trailing Zeroes
5 * Formula: E(sigma) limit (i=1..k) = [n/5^i]
6 * k is chosen such that 5^k+1 < n
7 * Execution Time: 1.49 (Alloted 8 Sec)
8 */
9
10 #include <iostream>
11
12 using namespace std;
13
14 int main() {
15 int n, trail_zeros;
16 long factor5, num;
17
18 cin>>n;
19 for (int i=0; i<n; i++) {
20 trail_zeros = 0;
21 factor5 = 5;
22 cin>>num;
23 while (factor5 <= num) {
24 trail_zeros += num / factor5;
25 factor5 *= 5;
26 }
27 cout<<trail_zeros<<endl;
28 trail_zeros = 0;
29 }
30 return 0;
31 }
32


The Program in bc (An arbitrary precision calculator language):

    0 define f(x) {
1 if (x>1) {
2 return (x * f (x-1))
3 }
4 return (1)
5 }
6
7 define z(x) {
8 if (0 == x) return 0;
9 if (0 == x%10) {
10 return 1+z(x/10)
11 }
12 return 0
13 }
14
15 define trial_zero(x) {
16 return z(f(x))
17 }
18