December 22, 2011

C Program to Calculate Factorial of Large Numbers

Many of you must have created a program to calculate the factorial of large numbers. You will use recursion, simple loop to calculate the factorial. The problem is not the method, problem comes up when I tell you to compute the factorial of the number 100. What  ? is it easy ?

Okay, Do you know that factorial of 100 contains 24 zeros at the end only if we leave the middle ones. The problem is to how to store this long number.

Code:
/*C Program to calculate factorial of large numbers ~ MyCFiles.com*/
#include<stdio.h>

struct fact
{
long long val[10000];
int till;
int zero;
};

typedef struct fact Fact;

Fact input[10000];

int main()
{
long long temp=0,i,j,pro=0;
int va;
input[0].val[0]=1;
input[0].till=1;
for(i=1;i<1010;i++)
{
for(j=0;j<input[i-1].till;j++)
{
pro=(input[i-1].val[j]*(i+1))+temp;
if(pro>=10)
{
input[i].val[j]=(pro%10);
temp=pro/10;
input[i].till=(j+1);
}
else
{
input[i].val[j]=pro;
input[i].till=(j+1);
temp=0;
}
}
if(temp>0)
{
while(temp>0)
{
input[i].val[j]=temp%10;
temp=temp/10;
j++;
input[i].till=j;
}
}
temp=0;
}
scanf("%d",&va);
for(j=input[va-1].till-1;j>=0;j--)
{
printf("%lld",input[va-1].val[j]);
}
return 0;
}

Sample Output:


Code Analysis:
We created a program that can calculate the factorial of numbers 1 to 1,000. Yes. We have used array to store the large number. One condition of the program is that your compiler must be able to handle the array large enough to handle the factorial of 1,000. That’s why we used CodeBlock IDE the used GCC compiler. Anyways, if you clearly look at the program, you will see that program first stores all the factorials from 1 to 1,000 first, then asks you for Input. It is done because in some cases, you need to calculate the factorial in the given time limit. Believe me that if you are going to start from scratch, you are never going to end computing in time. But here is the trick, time starts from the instant you took the input, it means first compute the result of all the imputs, store it, then show it as wanted.
Use CodeBlock IDE because TC++ can’t handle large array size. Download CodeBlock mingw-setup from here.
If you are new to CodeBlock, I got certain things for you,
use Ctrl+F9 -> Compile
and use Ctrl+F10 -> Run

Comment bello for your Query and Feedback

Related Posts :



0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Related Posts with Thumbnails