【发布时间】:2015-08-04 19:00:42
【问题描述】:
我需要一个递归函数来计算序列S=1! + 2! + 3! + ...+n!。
我已经使用 2 个函数完成了。
void main()
{
int terms=4;
printf(sum(terms)); //outputs 33
/*
terms is the number of terms in the series
e.g. terms=3 outputs 9, 4 outputs 33
*/
}
int fac(int n)
{
return n<2 ? 1 : n * fac(n-1) ;
}
int sum(int terms)
{
return terms>0 ? (fac(terms) + sum(terms-1)):0 ;
}
【问题讨论】:
-
使用循环执行选项之一?
-
您应该使用您正在使用的语言添加标签。
-
@anindya dutta -- 没有迭代,只有递归
标签: java c++ c recursion factorial