phfb.net
当前位置:首页 >> 用python求阶乘的和 >>

用python求阶乘的和

import mathprint math.factorial(3)+math.factorial(4)+math.factorial(5)

我们需要两个变量来改变和存储阶乘的变化,具体代码如下:def factorial(n): a,b=1,0 for j in range(n): b+=1 a*=b yield aprint(sum(tuple(factorial(3)))) 最后的输出结果是 9

#python 3.6.4sum = 0temp=1shu = int(input("请输入所求的一个数bai阶乘倒数du的累加和:zhi "))for i in range(1, shu+1): temp=temp*i sum=sum+1.0/temp print("1!+2!+..+{0}={1}".format(shu,sum))测试dao:请输入所求的一个数阶乘倒

可以用循环loop或递归来(recursion)来解决抄类似问题1. 应用袭loop:def factorial_loop(n): res = 1 for i in range((1,n+1): res *= i return res print factorial(15)2. recursion def factorial_recursion(n): if n <= 1: return 1 return n*factorial_recursion(n-1)

def jiezheng(n): if n==1 or n==0: return 1 return n*jiezheng(n-1)递归调用函数jiezheng算阶乘 jiezheng(5) 返回120

n,a=eval(input()) s=1 for i in range(1,n+1):s=s*i for k in range(1,n):ak=a**k aj=a**(k+1) if s%ak==0 and s%aj!=0:break print(k)

import functools print(functools.reduce(lambda x, y: x * y, range(2, 101, 2)))

def getDigits(data): digits = [] while data / 10: digits.append(data % 10) data /= 10 digits.append(data) print digits return digitsdef sumNfabric(data): digits = getDigits(data) digits.sort() print digits sumOfDigitsFabric = 0 fabric = 1 for i in xrange(1,

def factorial(n): if n == 1: return 1 else: return n * factorial(n - 1) input_num = input() try: with open('jc.txt', 'w') as file: file.write(str(factorial(int(input_num)))) except IOError as e: print('error', e)

def fact(n): if n==0: return 1 else: return n*fact(n-1) n=int(input()) print(fact(n))

网站首页 | 网站地图
All rights reserved Powered by www.phfb.net
copyright ©right 2010-2021。
内容来自网络,如有侵犯请联系客服。zhit325@qq.com