I have a solution for calculating the factorial, which works fine for at least n<=15000. Factorial of 10000 can be calculated under 1 sec and that for calculating the factorial takes less than 2 seconds. (Of course your question tells nothing about time constraints and these timings are totally dependent on the machine). Anyways, the concept is quite simple. I use a char array. The first character of the array is '1'. The LSBs are stored from the index starting with 0. A variable(m according to my program) keeps track of the factorial length. The final value of m is the number of digits in the factorial and the (m-1)th element of the char array is MSB of the factorial.
As the loop iterates, the characters get added in the right side of the array. A variable 'c' keeps track of the carry.
The drawbacks of using the array is left over chunks of unused bytes. And beyond a certain point, you cannot reserve space for an array.Besides, arrays tend to get slow.
You can check out my program on ideone: http://ideone.com/K410n7
I believe my solution can still be optimized. Please suggest how.
include<stdio.h>
char res[200000];
inline int fact(int n)
{
int i,j;
register int m,c;
m=1;
res[0]='1';
for(i=2;i<=n;i++)
{
c=0;
for(j=0; j< m; j++){
c =((res[j]-48)*i)+c;
res[j]=(c%10)+48;
c=c/10;
}
while(c>0){
res[m]=(c%10)+48;
c=c/10;
m++;
}
}
return m;
}
int main() {
int n,i,d;
scanf("%d",&n);
d=fact(n);
for(i=d-1;i>=0;i--)
printf("%c",res[i]);
return 0;
}