递归:n个项的和 [英] Recursion: Sum of series of n terms
本文介绍了递归:n个项的和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
需要递归函数
系列是:1 + 2 * 3 + 3 * 4 * 5 + 4 * 5 * 6 * 7 + ....
Series is: 1 + 2*3 + 3*4*5 + 4*5*6*7 + ....
递归查找n的序列之和。我无法考虑应该在函数中传递哪些参数。
Find the sum of the series for n recursively. I am not able to think of what parameters should I pass in function.
我的方法
我以为我应该传递n,要相乘的项数,但我无法想到的是,在同一函数中我应该如何+和*,我的return语句将是什么?
I thought that I should pass n, number of terms to be multiplied but what I am not able to think of is how should I + and * in same function and what will my return statement is?
推荐答案
function F(n, nmax, prod): Int
//prod = (prod div n) * (2 * n) * (2 * n + 1) simpler:
prod = prod * 2 * (2 * n + 1)
if n = nmax - 1
return prod
else
return prod + F(n+1, nmax, prod)
output F(1, 7, 1)
这篇关于递归:n个项的和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文