java - 仅使用一个递归函数计算 1 到 n 的阶乘之和

标签 java c++ c recursion factorial

我需要一个递归函数来计算序列 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/

相关文章:

python - Segmentation Fault shell代码测试kali 2018

MySQL C API : check if a field exists

java - 如何从网络项目创建 war 和 jar ?

java - Finally block 的实现

java - Selenium Java 中每个场景的 Chrome 和 Firefox 之间的更改(CUCUMBER、JUnit)

c++ - 为什么我不能让我的 CDatabase 对象理解我的数据源名称?

c++ - Qt 与 Visual Studio 宏问题

java - 定期从日志文件中读取数据

c++ - 使用 libc++ 正则表达式库 (C++11) 匹配 "beginning-of-line"

c# - WM_SIZING 上的 GetClientRect 给出了错误的大小