void Factorial(int n)
{
//假设n最大为1000, 1000的阶乘约等于4 * (10 的2567次方),可以用一个长度为3000的数组保存
const unsigned int MAX_COUNT = 3000;
/*
存放阶乘结果,按数组索引递增存放阶乘结果(个、十、百、千... => f[0],f[1],f[2],f[3]...),
之所以采用逆序结果是为了保证进位方便
*/
int f[MAX_COUNT];
int iData,curIndex;
memset(f,0,3000 * sizeof(int));
//0! = 1, 1! = 1;
f[0] = 1;
//2! = 2 * 1!, ...5! = 5*4!
for (iData = 2; iData <= n; ++iData)
{
int iRemain = 0;
for (curIndex = 0; curIndex < MAX_COUNT; ++curIndex)
{
int iCurBitRes = f[curIndex] * iData + iRemain;
f[curIndex] = iCurBitRes % 10;
iRemain = iCurBitRes / 10;
}
}
//翻转输出
//跳过有效高位后边的0
for (curIndex = MAX_COUNT-1; curIndex >= 0; curIndex--)
{
if (f[curIndex] != 0)
{
break;
}
}
for (; curIndex >= 0; --curIndex)
{
cout << f[curIndex];
}
cout << endl;
}
求N的阶乘
最新推荐文章于 2023-04-28 11:17:46 发布