我需要一个递归函数来计算序列 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 ;
}
最佳答案
这是我能得到的最简单的:
int sum_fac(int target, int counter) {
return (target == counter) ? target : counter * (1 + sum_fac(target, counter + 1));
}
当这样调用时:
int main() {
for (int i = 1; i < 10; i++) {
printf("%d: %d\n", i, sum_fac(i, 1));
}
}
输出这个:
1: 1
2: 3
3: 9
4: 33
5: 153
6: 873
7: 5913
8: 46233
9: 409113
关于java - 仅使用一个递归函数计算 1 到 n 的阶乘之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30402046/