### 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:
 ``12345678910111213`` ``````#include 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!="<

using "for" loop:
 ``1234567891011121314`` `````` #include 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!="<
> 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.

 ``123456789101112131415161718192021222324`` ``````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.