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

Time:04-11

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

CodePudding user response:

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