Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Write a function which takes n as a parameter, and returns the number of trailing zeros in n!.

Input Constraints

0 <= n <= 10^100

Output Constraints

Should be return the result in less than 10 seconds.

Test Input

1
213
45678
1234567
78943533
4567894123
121233112233112231233112323123

Test Output

0
51
11416
308638
19735878
1141973522
30308278058278057808278080759

Shortest code by character count wins.

share|improve this question
I'm not sure if we should have this here, as it's basically the same as spoj.pl/SHORTEN/problems/FACTZERO – Nabb Feb 8 '11 at 15:29
@Nabb, I had no idea that this question was on SPOJ. I've put a significantly larger limit on the input here though. – Dogbert Feb 8 '11 at 15:35
@Dogbert: The limit is larger but the algorithms here are going to be exactly the same as over at SPOJ. – Nabb Feb 8 '11 at 16:03
for shortest code, you should use the code-golf tag – gnibbler Feb 8 '11 at 19:54
It's on Euler as well :) (i think) – st0le Feb 9 '11 at 5:50
show 2 more comments

5 Answers

up vote 1 down vote accepted

Python

36 Chars Ripped from my earlier answer

f=lambda n:n//5+(n//5>0and f(n//5)or 0) #Py3k #39 Chars
f=lambda n:n/5+(n/5>0and f(n/5)or 0) #Before 3.0 #36 Chars
share|improve this answer
But you still need the input and output right? – Quixotic Mar 8 '11 at 23:59
@Debanjan, the question states, write a function.... – st0le Mar 9 '11 at 5:35
@sOle:My bad!I missed that. – Quixotic Mar 9 '11 at 6:05

Python 50 47 Characters

n=input()
x=5
s=0
while n/x:s+=n/x;x*=5
print s
share|improve this answer

Ruby: 52 43

n=gets.to_i;a=0;i=1
a+=n/i*=5while i<n
p a
share|improve this answer
You could use (a+=n/i;i*=5)while i<n to save a char. – Dogbert Feb 8 '11 at 15:51
And ofcourse, p a as a is a number. – Dogbert Feb 8 '11 at 15:54

Haskell (63)

f i=length$filter(\x->x`mod`5/=0)[1..i];main=interact$show.f.read
share|improve this answer

J - 26

f=:3 :'+/<.y%5^(1+i.144x)'

eg

   f 121233112233112231233112323123x
     30308278058278057808278080759
   f 4567894123
     1141973522
   f 0
     0
   f 10^100x
     2499999999999999...99999999999999999982

in less than a second for all input examples

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.