All rights are reserved by Niteesh Kumar.. Theme images by Storman. Powered by Blogger.

Followers

Total Pageviews

Blog Archive

Follow by Email

Translate

Monday, 21 September 2015

Finding factorial of large numbers.

We know that factorial of number greater than 50 is too large that we can not store it's value in any standard data type available.So, if we need to find the factorial of large numbers we will use an array to store the factorial value.
The concept is based on that we store single digit of factorial in reverse order to the array and multiply these numbers with the next number of the factorial sequence and each time when we have a carry on multiplying the last digit of array we will increase the size of array and store that carry value there.At last we will print the array in reverse order.

Example-    

We are storing 1 at a[0] and then multiply it with 2 and then 3 and so on..... till that number whose factorial we need.if in any case there is a carry the increase the size of array by 1.
Note that we are storing the result in reverse order like for the factorial of 5 and 6 result will be stored like 

5!=

 0
 2
 1






6!= 


 0
 2
 7



   
and I am printing the result in reverse order.       



#include <stdio.h>
#include <stdlib.h>
int main()
{
      int n,a[10000],i=1,j,c=0,k=1,l=0,m,p;
      scanf("%d",&p);
while(p>0)
{
        a[0]=1;      
        i=1,c=0,k=1,l=0;
        scanf("%d",&n);
    while(i<=n)
    {
      for(j=0;j<k;j++)
        {
                        m=i*a[j]+c;
                        a[j]=m%10;
                        c=m/10;
                        if(j==k-1)
                  if(c>0)
                         k++;
       }
c=0;
i++;
}
//print the array in reverse order
 for(j=k-1;j>=0;j--)
{  

    //check whether first digit is zero then remove it

    //as it comes while increasing size of array  

    if(a[j]!=0)
    l=1;
   if(l>=1)
   printf("%d",a[j]);
   }

for(i=1;i<=k;i++)
a[i]=0;
printf("\n");
p--;
}return 0;
}


      

0 on: "Finding factorial of large numbers."