大数据n!(n的阶乘)计算方法讨论
如题,以下是我找到的两种方法。
#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;
}
这两种的运行效率相差较大,大家还有更好的方法吗?