Friday, 25 September 2015

Efficient Program for Factorial using Memoization



#include <iostream>
using namespace std;
long long int cache[100000]={0};


long long int fact(long long int n)
{
if(n<=1)
return 1;
else 
    if(cache[n]>0)
return cache[n];
else
{
        long long int v=n*fact(n-1);
cache[n]=v;
return v;
}
}

int main()
 {
    long long int n;
   cin>>n;
   cout<<"Factorial of  "<<n <<"is = "<<fact(n);
   return 0;


}

No comments:

Post a Comment