您的位置:首页 > 大数据

大数据n!(n的阶乘)计算方法讨论

2007-10-17 15:23 330 查看
大数据n!(n的阶乘)计算方法讨论





yuhan_0110


欲寒

等 级:


发表于:2007-10-16 16:41:16 楼主
如题,以下是我找到的两种方法。

#include <stdio.h >
#include <time.h >
void main()
{
int n = 10000;
int a[50000] = {0};
a[0] = 1; //用数组的一项存放计算结果的位数
a[1] = 1; //将第一项赋值为一

//计算
clock_t time_begin = clock();
for(int j= 2; j <=n; j++)
{
int c = 0; //c表示向高位的进位
for(int i=1; i <=a[0]; i++)
{
a[i] = a[i] * j + c;//将来自低位的计算结果和本位的结果相加
if( c=a[i]/10 )
{
a[i] = a[i] % 10;
}
}

for(; c != 0; i++)
{
a[i] = c%10;
c = c / 10;
}
a[0] = i - 1;
}
clock_t runtime = clock()-time_begin;
printf("Runtime:%ld/n",runtime);

//输出
printf("位数=%d/n",a[0]);

printf("值=");
for(int x=1; x <=a[0]; x++)
{
printf("%d",a[a[0]-x+1]);
}
printf("/n");
}

#include <stdio.h >
#include <time.h >
int main(int argc, char *argv[])
{
long n=10000;

long a[4*10000] = {0};
a[0]=1;

long i,j,c,temp,len;
temp=0;
len=1;

//计算
clock_t time_begin = clock();
for(i=1; i <=n; i++)
{
c=0;
for(j=0;j <len;j++)
{
temp=a[j]*i+c;
c=temp/100000;
a[j]=temp%100000;
}
while(c >0)
{
len=len+1;
a[len-1]=c;
c/=100000;
a[len-1]%=100000;
}
}
clock_t runtime = clock()-time_begin;
printf("Runtime:%ld/n",runtime);

//输出
printf("%ld",a[len-1]);
for(i=len-2;i >=0;i--)
printf("%05ld",a[i]);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: