This challenge looks familiar - I think I answered something similara similar challenge on our sister site, Programming Puzzles and Code GolfProgramming Puzzles and Code Golf. Those answers may not be as readable, though.
There's a couple of pieces of good news:
- You don't need to count 2's in the prime factorization. There will always be more 2's than 5's, so you can never have an unpaired 5.
- You don't need to iterate over every number up to
num
if you see that we're just computingn/5 + n/25 + n/125 + ...
(integer division). If we definef(n) = n/5 + f(n/5)
andf(0) = 0
, we have a much faster version. That can be implemented recursively, or fairly easily converted to iterative form.