您的位置:首页 > 其它

原创:大数阶乘的讨论(1)

2007-07-23 20:26 197 查看
阶乘一般定义为n!=nx(n-1)x(n-2)...x2x1

用普通函数可以表示为

int fact(int n)

{

int r;

while(n!=1)

{

r*=n;

--n;

}

return r;

}

也可以用函数递归形式

int fact(int n)

{

if(n==0)

return 1;

else

return n*fact(n-1);

}

但是由于计算机本身的限制,在32位机上最多只支持到2^32-1约为13!这显然不能满足巨数阶乘的需求。

现有一法,相信很多人都能想到的:科学计数法

利用一个double存储数字部分,一个uint存储指数,比如:120=1.2x10^2

具体实现方法:

fact(int n)

{

unsigned int exponent=0;
double bottom;
int i;

while(1){
bottom=1;
exponent=0;
for(i=2;i<=n;i++)
{
bottom*=i;
while(bottom>=10)
{
bottom/=10;
exponent++;
}
}

if(exponent<=9)
{
for(i=1;i<=exponent;i++) bottom*=10;
printf("%d! = %.0lf/n",n,bottom); //若阶乘小于10位,就不用科学计数形式
}
else
printf("%d! = %lfe+%d/n",n,bottom,exponent); //以科学计数形式输出
}

}

在我的电脑上,计算100,000,000!(10亿)阶乘只需要16s左右的时间,应该说相当快了。

100,000,000!=1.617204e+756570556
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: