由于大数的阶乘已经超过整型所能够表示的最大值,属于大数操作问题,需要采用字符串进行操作。本文对n进行阶乘求取,分解为两个函数:void Multiply(char *s1,char *s2,char*out)//计算两个字符串的乘积,结果存入字符串void CalcNN(int n, char *pOut)//计算n的阶乘,结果存入字符串C语言的源代码如下:
void Multiply(char *s1,char *s2,char*out)
{
int lengthFirst = strlen(s1);
int lengthSecond = strlen(s2);//输出最多位数为两个长度相加
int i;
int j;
int k=lengthFirst+lengthSecond;
int tempOne;
int tempTwo;
int tempMultiply;
//out 在外部需被清空为'0'
memset(out,'0',lengthFirst+lengthSecond);
out[lengthFirst+lengthSecond]='\0';
for (i=lengthFirst-1;i>=0;i--)
{
tempOne = s1[i] -'0';
k = i+lengthSecond;
for(j=lengthSecond-1;j>=0;j--)
{
tempTwo = s2[j] - '0';
tempMultiply = tempOne * tempTwo;
if(tempMultiply > 9)
{
out[k] += (tempMultiply % 10);
if(out[k]> '9') //和上次相加后大于9,则需要再次进位
{
out[k] = out[k] - 10;
out[k-1] =out[k-1]+1;
}
out[k-1] += (tempMultiply / 10);
k--;
continue;
}
out[k] += tempMultiply ;
if(out[k]>'9')
{
out[k] = out[k] - 10;
out[k-1] =out[k-1]+1;
}
k--;
}
}
if ('0'==out[0])//有可能首位为‘0’;
{
for(i=0;i<lengthSecond+lengthFirst-1;i++)
{
out[i] = out [i+1];
}
out[i] = '\0';
}
return;
}
void CalcNN(int n, char *pOut)//计算n的阶乘.
{
int i;
char s1[1000]="";
char s2[1000]="";
char out[1000]="";
if (1==n||0==n)
{
pOut[0]='1';
pOut[1]='\0';
return;
}
strcpy(s1,"1");
for(i=1;i<n;i++)
{
itoa(i+1,s2,10);
Multiply(s1,s2,out);
strcpy(s1,out);
}
strcpy(pOut,out);
}