I have memoized the factorial function in C as follows:
int fact(int n)
{
int temp;
int lookup_table[n];
if(lookup_table[n])
return lookup_table[n];
else{
if(n == 0 || n == 1)
return 1;
else
temp = n * fact(n-1);
lookup_table[n] = temp;
return temp;
}
}
But then wehn I input n = 5 ,it ouputs
-1! = 134514064
Can someone please explain what is happening?
int lookup_table[n]should be marked static (actually it can’t, you need a constant there, but it doesn’t have to be too big as factorials grow very quickly), but its not really why you are getting a wrong answer. Instead,lookup_tableis initialized to indeterminate junk, instead of 0’s.However, theres no reason to initialize it to zero when you make it static; that will be done automatically.
Oh, and as others have pointed out, you have an out of bounds error because you need to exchange
int lookup_table[n]to use a constant rather thann.