我有一系列的数字需要求和。第一次迭代运算的值是1,第二次迭代运算的值是20。接下来的每次迭代都使用公式n*(n+1)/2中的前一个结果,因此第三次迭代,即i03=20*(20+1)/2,第四次迭代,即i04=i03*(i03+1)/2。这一直持续到i20=i19*(i19+1)/2的第20次迭代。我想用回忆录来做这件事。这是我的密码:
def outFun():
def sumFun(squares, total = 0, CONST = 20):
if squares > 2:
total = sumFun(squares - 1) * int((sumFun(squares - 1) + 1) / 2)
elif not squares - 2:
total = CONST
return total
return 1 + sumFun(20)
我做错什么了?你知道吗
你在打电话吗
两次!你知道吗
为什么不引入一个变量来存储结果呢?比如:
我是这样理解你的问题的:你有一个公式
x_n = x_{n-1} * (x_{n-1} + 1)/2
,递归基被定义为x_1 = 20
(或x_2 = 20
)?你的描述不清楚)。求解递归的最有效方法是自下而上方法,当您从x_1
开始,然后计算x_2
等。另一种方法是使用动态规划/记忆:印刷品
f(20)
打印有点大,所以我将打印其中的位数:代码在我的桌面上运行大约需要9秒钟:
相关问题 更多 >
编程相关推荐