DonHunt7382
DonHunt7382

Reputation: 37

How to do integer factorial compute by recursion using increasively number?

Here is the decreasing solution for factorial recursion :

int fact(int n)
{
     if (n == 0 || n == 1){
          return 1;
     } else {
          return n * fact(n - 1);
     }
}

If I want to do factorial recursion by increasing instead of decreasing :

int fact(int n, int i)
{
     if (n == 0 || n == 1){
          return 1;
     } else {
          if (i+1 <= n) {
               return n * fact(n, i + 1);
          }
          return n;
     }
}

It returned 15625 when I called fact(5, 0)

Thanks in advance

Upvotes: 0

Views: 65

Answers (1)

Abhay Pratap Singh
Abhay Pratap Singh

Reputation: 121

int fact(int n, int i)
{
     if (n == 0 || n == 1){
          return 1;
     } else {
          if (i+1 <= n) {
               return n * fact(n, i + 1);
          }
          return n;
     }
}

In above function, you are calculating n^{n} instead of n! due to return n * fact(n, i+1) statement.

Below recursion function(with minimum changes from the original function that OP posted) will work if we call it as fact(n, 0)

int fact(int n, int i)
{
     if (n == 0 || n == 1){
          return 1;
     } else {
          if (i+1 < n) {
               return (i+1) * fact(n, i + 1);
          }
          return n;
     }
}

Upvotes: 3

Related Questions