您的位置:首页 > 其它

输出L内所有数字的乘积末尾0的个数

2014-02-26 10:07 274 查看
思路:将10分解为2*5,注意这里只能分解为2*5,所以我们可以将列表L内的数字分解为因数2和5的个数。

python非递归代码

def zerocount(L):
count_2 = 0
count_5 = 0
#calculate count 2 and 5
for i in L:
temp = i
while temp%2 == 0:
temp = temp /2
count_2 += 1
temp = i
while temp%5 == 0:
temp = temp / 5
count_5 += 1
print count_2,count_5

#get small count
small = count_2
if small > count_5:
small = count_5
return small

L = [2,8,3,50]
print zerocount(L)


python递归版本

import os,sys

def divisorNum(value,divisor):
if value % divisor != 0:
return 0
else:
return 1+divisorNum(value/divisor,divisor)

def zerocount(L):
count_2 = 0
count_5 = 0
#calculate count 2 and 5
for i in L:
count_2 += divisorNum(i,2)
count_5 += divisorNum(i,5)
print count_2,count_5

#get small count
small = count_2
if small > count_5:
small = count_5
return small

L = [2,8,3,50]
print zerocount(L)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: