Search code examples
javac++crecursionfactorial

Sum of factorials of 1 to n using only one recursive function


I need a single recursive function to compute the series S=1! + 2! + 3! + ...+n!.

I've done it using 2 functions.

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 ;
}

Solution

  • This is the simplest I could get it:

    int sum_fac(int target, int counter) {
        return (target == counter) ? target : counter * (1 + sum_fac(target, counter + 1));
    }
    

    Which when called like this:

    int main() {
      for (int i = 1; i < 10; i++) {
        printf("%d: %d\n", i, sum_fac(i, 1));
      }
    }
    

    Outputs this:

    1: 1
    2: 3
    3: 9
    4: 33
    5: 153
    6: 873
    7: 5913
    8: 46233
    9: 409113