仅使用一个递归函数的1到n的阶乘的和

时间:2015-05-22 16:52:31

标签: 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 ;
}

4 个答案:

答案 0 :(得分:1)

这是我能得到的最简单的方法:

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

答案 1 :(得分:0)

int main() {
   sum(1,terms,1,0);
}

int sum (int cur, int terms, int fac, int sumcur) {

    return terms == n? sumcur: sum(cur+1, terms, (cur==1)?1:cur*fac, sumcur+cur*fac);
}

答案 2 :(得分:0)

你可以拥有这样的东西:

int sumOfFac(int currentNumber, int lastSum, int lastFac, int maxNumber)
{
    int currentFac = currentNmber*lastFac;
    int currentSum = lastSum+currentFac;

    if(currentNumber < maxNumber)
    {
        return sumOfFac(currentNumber+1, currentSum, currentFac, maxNumber);
    }
    return currentSum;
}

然后您第一次使用以下方法调用该函数:

currentNumber = 1
lastSum = 0
lastFac = 1
maxNumber = your n

答案 3 :(得分:0)

a_1 = 1!
a_2 = 1!+2!
...
a_n = a_(n-1) + f_(n-1)*n

其中f_i = i!。所以基本上我们需要来自dunction的两个输出 - af。让我们把它翻译成代码:

int series(int n, int *f)
{
    int a, f1;
    if (n < 2)
    {
        *f = 1;
        return 1;
    }
    else
    {
        a = series(n-1, &f1);
        *f = f1 * n;
        return a + (*f);
    }
}

然后

int main(void) {
    int dummy;
    printf("%d\n", series(1, &dummy));
    printf("%d\n", series(2, &dummy));
    printf("%d\n", series(3, &dummy));
    printf("%d\n", series(4, &dummy));
    return 0;
}

打印出来:

1
3
9
33


更新:
 为了进一步重构,我们可以说f_n = a_n - a_(n-1),所以f_(n-1) = a_(n-1) - a_(n-2)。那么递归的情况将是:

a_n = a_(n-1) + (a_(n-1) - a_(n-2))*n

这不需要计算f,但需要一些额外的bse案例和额外的递归调用:

    int series(int n)
    {
        int a1, a2;
        if (n <= 1)
        {
            return 1;
        }
        else if (n==2)
        {
            return 3;
        }
        else
        {

            a1 = series(n-1);
            a2 = series(n-2);

            return a1 + (a1 - a2)*n;
        }
    }