请指教,谢谢!
//下面这个计算10000!的程序供楼主参考
//用"万进制"计算万以内的阶乘(含10000)
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
short mul(short a[],short d,short x)
{ long i,y=0;
for(i=0;i<d;i++)
{ y+=a[i]*(long)x;
a[i]=(short)(y%10000);
y/=10000;
}
a[d]=(short)y;
return d+!!y;
}
void main()
{
long s;
short *a,i,j,n,ws=1;
printf("N=");scanf("%d",&n);
#define Pi 3.14159265358979323846L
s=(long)((log(2*Pi*n)/2+n*(log(n)-1))/log(10)+1);
a=(short*)malloc((s/4+2)*sizeof(short));*a=1;
for(i=2;i<=n;i++)
ws=mul(a,ws,i);
printf("%d!=%d",n,a[ws-1]);
for(j=ws-2;j>=0;j--)
printf("%04d",a[j]);
printf("\n");
free(a);
}
//用VC++6.0(内嵌汇编)计算整数的阶乘因而速度较快
//如在本人奔Ⅳ的机器上,计算10万的阶乘历时55.7秒
//(当然显示运算结果的时间不算在内)
//本程序原则上可计算10亿以内的阶乘
//实际受到虚拟内存和时间方面的限制
//计算100万的阶乘预计需要2小时左右
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <climits>
#include <cmath>
#include <cfloat>
#include <windows.h>
using namespace std;
typedef unsigned long int Long;
class Factorial
{
private:
Long n;
Long base; //进制数取10亿
Long*low; //阶乘值最低位的地址(是静止不变的)
Long*high; //当前最高非零位地址(是动态调整的)
Long length;//length表示base进制下n阶乘的“位”数
Long*result;//动态数组名,用于存放阶乘值
void setLength()//确定在base进制下n阶乘有多少“位”
{
const double Pi=3.14159265358979324;
double LOG=n*log(n)-n+log(2*Pi*n)/2+1./12/n;
//数学中用于计算ln(n!)的公式(过剩近似)
cout<<n<<"阶乘是"<<1+int(LOG/log(10))
<<"位的整数(十进制)\n";
length=1+LOG/log(base);
}
void mul(Long jj)
//让j与result数组中的大整数相乘,乘积仍放在result中
{
Long *pp = low;
Long *qq = high;
_asm mov ecx,0
_asm mov ebx,1000000000
_asm mov edi,pp
_asm mov esi,jj
next:
_asm mov eax,[edi]
_asm mul esi
_asm add eax,ecx
_asm adc edx,0
_asm div ebx
_asm mov ecx,eax
_asm mov [edi],edx
_asm sub edi,00004
_asm cmp edi,qq
_asm jnb next
_asm and ecx,ecx
_asm jz done
_asm mov [edi],ecx
high --; //如有进位就调整high
done : ;
}
public:
Factorial(Long n)//构造函数定义
{
this->n = n;
base=1000000000;//base应为10的整数次幂
setLength();//让this->length获得适当值
result= new Long[length];//申请动态数组
}
~Factorial()//析构函数定义
{
if(result)delete[]result;
}
void display()//显示阶乘计算结果
{
cout <<"factorial("<<n<<")=";
cout << result[0];
for(long i=1; i<length; i++)
{
cout<<setfill('0')<<setw(9)<<result[i];
//域宽9=log10(base)即10亿进制下每次显示9位
}
cout << endl;
}
void fact()//阶乘的计算
{
memset(result,0,length*sizeof(Long));
result[length-1] = 0000001;
high=low=&result[length-1];
for(Long j=2;j<=n;j++)
{
__int64 temp = j;
while(j+1<=n && temp<base)
temp*=++j;
if(temp>=base)
temp/=j--;
mul(temp);
}
//以上粗体可简化为mul(j);只是速度稍慢
}
};
void main()
{
Long num; cout<<"n="; cin>>num;
LARGE_INTEGER start,finish,freq;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter( &start);
Factorial fac(num);
fac.fact();
QueryPerformanceCounter(&finish);
fac.display();
double sec =
double(finish.QuadPart-start.QuadPart)/freq.QuadPart;
cout<<"计算耗时"<<sec<<"秒"<<endl;
}
[此贴子已经被作者于2007-6-16 10:58:07编辑过]