// 阶乘.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdio.h>
#include <math.h>
#include <stdlib.h> /* 求N!的位数公式 log10(1)+log10(2)+···+log10(n) 取整加1 */
int wei(int n)
{
int i;
double sum=0;
for(i=1;i<=n;i++)
sum+=log10((double)i); /* 以万为进制,一位可以表示4个数,减少存储空间 */
return (int)((sum+1)/4+1);
} /* 高精度阶乘核心 */
int _tmain(int argc, _TCHAR* argv[])
{
int i,j,n,k,m=0,jinwei,weishu=1,temp;
unsigned int *x;
scanf("%d",&n); /* 依据阶乘位数申请动态数组 */
x=(unsigned int*) malloc(wei(n)*sizeof(int));
x[0]=1;
for(i=2;i<=n;i++)
{
jinwei=0;
for(j=1;j<=weishu;j++)
{
temp=x[j-1]*i+jinwei;
if (temp>=1)
{ /* 以万为进制,提高运算速度 */
x[j-1]=temp%10000;
jinwei=temp/10000;
}
}
while(jinwei)
{
weishu++;
x[weishu-1]=jinwei%10000;
jinwei/=10000;
}
} /* 先输出第一个数,防止首位出现0 */
printf("%d",x[weishu-1]);
for(j=weishu-2;j>=0;j--) printf("%04d",x[j]); /* 输出其余的数,因为万进制,需要补0 */
system("pause");
return 0;
}