Wednesday, November 13, 2013

C Program to Find Factorial Of LARGE NUMBERS

Today's post is all about calculating factorial. Seems to be easy at first look, calculating factorial is not that easy and you can believe that  from the experience of a guy who has lost a bet and a career opportunity due to this.

yes career opportunity.. that's another story which i will write, but later...

Approach #1:

The naive approach will be to run a loop till that number and storing the multiplication in a variable from 1 to that number and finally displaying the result.
But, there's a flaw in this approach, while multiplying numbers as soon as the data goes out OF RANGE of that number there will be discrepancy in the result, No matter you increase the size of data type. even long long unsigned int is not enough even for calculating the factorial of a small number like 55 or 60.   

Approach#2:

I learned from experience that whenever you are struck with something go back to the basics.
we will do the multiplication here exactly the same way we used to do in our maths class.
We will use arrays to store the number and perform multiplication on single integer index by index.

Here's the code for the implementation:

#include<stdio.h>
#define max 10000
void factorial(int);
void multiply(int);
int length=0;
int fact[max];


void factorial(int num)
{
    int i;
    for(i=2;i<=num;i++)
        multiply(i);
}
void multiply(int num)
{
    long i,rem=0;
    int j;
    int arr[max];
    for(i=0;i<=length;i++)
        arr[i]=fact[i];

    for(i=0;i<=length;i++)
    {
        fact[i]=((arr[i]*num)+rem)%10;
        rem=((arr[i]*num)+rem)/10;
    }

 if(rem!=0)
 {
     while(rem!=0)
     {
         fact[i]=rem%10;
         rem=rem/10;
         i++;
     }
 }

    length=i-1;
}
int main()
{
    int num,i;
    printf("\nEnter number whose factorial is to be calculated\n");
    scanf("%d",&num);
    fact[0]=1;
    factorial(num);
    printf("\nFactorial is: \n");
    for(i=length;i>=0;i--)
        printf("%d",fact[i]);

    return 0;

}

Have fun it's an easy code to understand. Comments below if you have any doubt's or suggestions. :)

Viva La Raza
Sid



No comments:

Post a Comment