ACM竞赛中另一个基础运算,大数的阶乘(factorial),其实阶乘中要算超出int表示范围的阶乘这是个十分浩瀚的工程,其实就是很多个大数先乎乘积再求和。
真不敢想象一个位数超过百位的数字,它的阶乘,这个目前不考率,^_^,这样的话就大大降低了复杂度和难度。
这个无非就是大数相乘的思路了。废话不多说,上代码。我的这个效率属于比较低的那种,也是模拟手算过程的程序化。
code:
#include<cstdio>
#include<cstdlib>
const int Max = 500;
int rslt[Max];
void Factorial(int n)
{
rslt[0] = rslt[1] = 1;
int indx;
if(n==1||n==0)
return;
for(int i=2;i<=n;i++)
{
indx = 0;
int pre = 0,j; //the symbal of carry set
for( j=1;j<=rslt[0];j++)
{
rslt[j] *=i;
rslt[j] += pre;
pre = rslt[j]/10;
rslt[j] %= 10;
}
while(pre) //process the last byte
{
rslt[j] = pre%10;
rslt[0] = j;
pre /= 10;
j++;
}
}
for(int Ick=rslt[0];Ick>=1;Ick--)
printf("%d",rslt[Ick]);
printf("\n");
}
void Init()
{
for(int i=0;i<Max;i++)
rslt[i] = 0;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
Init();
Factorial(n);
}
return 0;
}
转载于:https://blog.51cto.com/jeick/544374