通常解决大数运算数据超出范围,溢出的问题。一般采用数组去模拟。求算n!可以看成是每次两个整数相乘的过程,因此可以模拟成大数相乘的过程。只是需要增加一些变量去存储中间的进位和当前位的数值。
#include <iostream>
using namespace std;
#define MAX_WEI 100000
int result[MAX_WEI];
int wei_location;
int up;
int main()
{
int i,n;
int j;
while(scanf("%d",&n)!=EOF)
{
memset(result,0,sizeof(result));
result[1] =1;
wei_location=1; //当前结果的位数,便于相乘和最后输出
up =0;
if(n==0 || n==1)
{
printf("1\n");
continue;
}
for(i=2;i<=n;i++) //n!中的每个数
{
for(j =1,up =0;j<=wei_location;j++) //模拟乘法步骤:每一位与当前数相乘
{
result[j] = result[j] *i + up; //当前数+前面的进位数
up = result[j]/10;
result[j] =result[j]%10; //每个数存一位
}
while(up > 0)
{
result[j++] += up%10; //注意跳出来是j是多一的
up= up/10;
}
wei_location= j -1;//注意跳出来是j是多一的
}
for(i = wei_location;i>=1;i--)
(i!=1)? printf("%d",result[i]) : printf("%d\n",result[i]);
}
return 0;
}
原文:http://blog.csdn.net/happy_cheng/article/details/43114541