我需要创建一个函数,在这个函数中我应该得到N!
的最后一个非零数位。
下面的代码返回一个错误的答案。
def get_last_nonzero_elem(n):
if 0 <= n <= 1000000:
factorial = reduce(lambda x, y: x * y,[1] + range(1, n+1))
list_factorial = map(int, str(factorial))
for i in reversed(list_factorial):
if i != 0:
return i
else:
return None
我在这里做错了什么?
发布于 2017-02-19 10:42:50
一旦你得到阶乘,只需这样做:
a = str(factorial)
output = int(a.replace('0', '')[-1])
假设您的n
对于将其阶乘存储在int
中来说并不太大。否则,使用lists
来计算大数的阶乘。
发布于 2017-02-19 11:34:38
请参阅以下代码:
def fact(n):
if n==0:
return 1
else :
return n*fact(n-1)
x = fact(44) # x =2658271574788448768043625811014615890319638528000000000L
y=str(x)[::-1] # convert x to string and invers it
str(int(y))[0] # convert y to int after to string and get the first char
#8
发布于 2017-02-19 11:58:42
没有递归限制,内存使用率低,这一点:
from functools import reduce
def fact(n):
if n==0:
return 1
else :
# in python 2 replace range by xrange:
return reduce(lambda x, y: x * y, range(1, n+1))
def last_non_zero(n):
while n:
d = n%10
if d!=0:
return d
else:
n //= 10
N = 1000
f = fact(N)
print("factorial of {} is : {}".format(N, f))
print("last non zero is:", last_non_zero(f))
https://stackoverflow.com/questions/42326154
复制相似问题