should i use a recursive function or a "for" loop to calculate the factorial of a number?

so i have two pieces of code,both perform the same task "which is to calculate the factorial of a specific number",but the first one does this using a recursive function,while the other one does this using a "for" loop.
which method should i use in order not to exhaust the memory?.

using recursive function:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

unsigned int factorial(unsigned int number) {
    if (number==0 || number==1) {
        return 1;
    }
    return number*factorial(number-1);
}

void main() {
    cout<<"5!="<<factorial(5)<<endl;
}


using "for" loop:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
 #include <iostream>
using namespace std;

unsigned int factorial(unsigned int number) {
    int i,result=1;
    for (i=number;i>0;i--) {
        result=result*i;
    }
    return result;
}

void main() {
    cout<<"5!="<<factorial(5)<<endl;
} 
> which method should i use in order not to exhaust the memory?

It does not matter; the compiler would generate the same code for both.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
static unsigned int factorial_r( unsigned int number ) {
  
    if ( number==0 ) return 1;
    else return number * factorial_r(number-1);
}

static unsigned int factorial_i( unsigned int number ) {
  
    unsigned int result = 1;
    for( unsigned int i = number; i>0; --i ) result=result*i;
    return result;
}

unsigned int foo() { 
  
  return factorial_r(10) ; 
  // rewrittten by the compiler as: return 3628800 ;
}

unsigned int bar() { 
  
  return factorial_i(10) ; 
  // rewritten by the compiler as return 3628800 ;
}

https://godbolt.org/g/9KoR1X
neither.
use a lookup table of about 25-30 values, unless you are pulling in an extension that can handle the larger values. This can just be a global const array, and your function call looks like

z = fact_table[value];


Last edited on
Topic archived. No new replies allowed.