Saturday, May 29, 2010

Find factorial of any number !!

Finding factorial of a number is a requirement that one can come across in many problems. With the limited size of the data types in the high level languages, it is impossible to store these factorial values in a single variable of a particluar datatype. For example the value of 100! is 181 digits long and we certainly got no data type to store such a large value...

So here's how to find factorial of any given number., say 100
We create an array of 100000 digits(just to fit in factorial of bigger numbers) dynamically since its essential to pick up this memory from heap. Then, create a loop which decrements the value by 1 each time and multiplies the result by the decreased value. Following this way, after 100 iterations we finally get the factorial of 500 in an array of size 181. Considering that every element is an integer, the total space required to store this result would be 181*4= 724 bytes.

The source code is as follows :


// factorial of positive integers :

#include
#include
#define M 100000 // defines the size of the array that would store the factorial
using namespace std;

long long *farr=new long long[M];
int counter;

void func(int aindex)
{
    int k=0;
    int findex=0;
    int temp=0;
    int carry=0;
  
    while(k++<=counter)
    {
      temp=farr[findex]*aindex;
      farr[findex++]=(temp+carry)%10;
      carry=(temp+carry)/10;
    }

     findex--;
  
     if(carry)
     {
         if(carry<10)
         {
          findex++;          
          farr[findex]=carry;  
          counter++;
         }
        
         else
           {
                 while(carry)
                 {
                      findex++;      
                      farr[findex]=carry%10;
                      carry/=10;
                      counter++;
                 }  
           }
     }
}


int main()
{
    int h;
    cin>>h;

   for(int i=0;i
    farr[i]=1;
  
    while(h>0)
    {
            func(h);
            h--;
    }
  
    cout<<"result  :  ";
    for(int i=counter;i>=0;i--)
     cout<

   getch();
}

To solve more problems of this kind:
http://projecteuler.net/index.php?section=problems&id=20