导航

[原]一道面试题,计算n!结尾0的个数

Posted on 2010-10-09 16:29  maconel  阅读(311)  评论(0)    收藏  举报

一道面试题:给定自然数n,请问n!的结尾有多少个0。

例如n=10,那么10!=3628800,结尾有2个0。

 

程序如下:

1 #coding:utf-8
2  
3  def count_tail(n):
4 def power5(max):
5 p = 5
6 while p <= max:
7 yield p
8 p *= 5
9 count = 0
10 pn = power5(n)
11 for i in pn:
12 count += int(n / i)
13 return count
14
15 print count_tail(4)
16 print count_tail(5)
17 print count_tail(6)
18 print count_tail(7)
19 print count_tail(12)
20 print count_tail(55)
21 print count_tail(101)
22 print count_tail(1000)
23 print count_tail(10000)
24 print count_tail(99999)

输出:

1 0
2 1
3 1
4 1
5 2
6 13
7 24
8 249
9 2499
10 24994