您的位置:首页 > 其它

高精度大整数模板(n!为例)

2016-10-30 20:28 302 查看
如求n!

1.打表(就是个想法,显然会超内存,数据范围1000可以)

#include <iostream>
#include <cstdio>
using namespace std;
const int N=100000;
const int M=10001;
int a[M][7200];
void fun()
{
a[1][1]=1;
a[2][1]=2;
for(int i=3;i<M;i++)
{
int tmp=0;
for(int j=1;j<=7200;j++)
{
tmp+=a[i-1][j]*i;//只要换这里的递推公式
a[i][j]=tmp%N;
tmp/=N;
}
}
return;
}
int main()
{
fun();
// for(int i=1;i<=7200;i++)
// cout<<a[10000][i]<<" ";
int n;
while(~scanf("%d",&n))
{
int i=7199;
while(a
[i]==0)i--;
printf("%d",a
[i--]);
for(;i>0;i--)
printf("%05d",a
[i]);
printf("\n");

}
return 0;
}
另外,容易超内存的模板,求n!在10000以内就不要这样打表

虽然上面的方法省略了进位的处理,会方便些,但容易mle,若加上进位处理的模板(不打表):

2.不打表,直接求
#include<cstdio>
#include<cstring>

#define N 8000
int s
;
int main()
{
int n;
int i,j,t,y;
while(scanf("%d",&n)==1)
{
if(n==0)
{
printf("1\n");
continue;
}
memset(s,0,sizeof(s));
s[1]=1;
t=1;
for(i=2; i<=n; i++)              //s数组的所有位数表示当前计算出的结果
{
y=0;
for(j=1; j<=t; j++)
{
s[j]=s[j]*i+y;
y=s[j]/100000;
s[j]%=100000;
}
while(y)                     //有余进位
{
s[++t]=y%100000;
y/=100000;
}
}
printf("%d",s[t]);              //去前置零
for(i=t-1; i>=1; i--)
printf("%05d",s[i]);        //格式化输出,每一个s代表了结果中的5位数
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: