关于用加法实现大数的阶乘
Lersh 2001-02-08 07:22:00 上次我提问如何计算大数的阶乘,根据Tice(孤笑)提供的思路;5!=4!+4!+4!+4!+4!,4!=3!+3!+3!+3!,3!=2!+2!+2!,2!=1!+1!。
按此思路,我编了一个程序,从0到6都正确,7不对,8又对了,以后都不正确!我找不出原因,望大家相助!为了方便,给出DOS下的源程序。
#include "stdlib.h"
#include "math.h"
main()
{
int times,size,Number,j,i,k;
float length=0;
char * result,* temp;
printf("\nPlease input the Number:");
scanf("%d",&Number);
for(i=1;i<=Number;i++)
length+=log10(i);//计算长度
size=(int)length+1;
result=malloc(size*sizeof(char));//分配空间
printf("%d\n",size);
temp=malloc(size*sizeof(char));
for(i=0;i<size;i++)
result[i]=0;
result[0]=1;
length=0;
for(i=0;i<size;i++)
temp[i]=result[i];
//以下是核心算法
for(times=1;times<=Number;times++)
{
for(i=1;i<=times-1;i++)
length+=log10(i);
for(i=1;i<=times-1;i++)
{
if(i==1)
for(k=0;k<=(int)length;k++)
temp[k]=result[k];
for(j=0;j<=(int)length;j++)
{
result[j]+=temp[j];
if(result[j]>=10)
{
result[j+1]+=result[j]/10;
result[j]%=10;
}
}
}
}
for(k=size-1;k>=0;k--)
printf("%c",result[k]+'0');
getch();
}