专题 高精度看了也不懂

算法简介

高精度算法,属于处理大数字的数学计算方法。在一般的科学计算中,会经常算到几千亿几百亿的大数字。一般这类数字我们统称为高精度数,高精度算法是用计算机对于超大数据的一种模拟加,减,乘,除,乘方,阶乘,开方等运算。对于非常庞大的数字无法在计算机中正常存储,于是,将这个数字拆开,拆成一位一位的,或者是四位四位的存储到一个数组中, 用一个数组去表示一个数字,这样这个数字就被称为是高精度数。高精度算法就是能处理高精度数各种运算的算法,但又因其特殊性,故从普通数的算法中分离,自成一家。

在本篇中,我们给出压位高精度的加减乘除模板。

算法实现

#include <bits/stdc++.h>
using namespace std;

const int MAXN=101000;
const int power=4;
const int base=10000;

struct Big
{
	int a[MAXN];
	Big(){memset(a,0,sizeof(a));}
	Big(char *s)
	{
		reverse(s,s+strlen(s));
		memset(a,0,sizeof(a));
		int len=strlen(s);
		a[0]=(len+power-1)/power;
		for(int i=0,t=0,w;i<len;w*=10,++i)
		{
			if(i%power==0) w=1,++t;
			a[t]+=w*(s[i]-'0');
		}
	}
	void add(int k) {if(k||a[0]) a[++a[0]]=k;}
	void re() {reverse(a+1,a+a[0]+1);}
	void print()
	{
		printf("%d",a[a[0]]);
		for(int i=a[0]-1;i>0;--i)
			printf("%04d",a[i]);
		printf("\n");
	}
};

bool operator < (const Big &p,const Big &q)
{
	if(p.a[0]<q.a[0]) return true;
	if(p.a[0]>q.a[0]) return false;
	for(int i=p.a[0];i>0;--i)
		if(p.a[i]!=q.a[i]) return p.a[i]<q.a[i];
	return false;
}

Big operator + (const Big &p,const Big &q)
{
	Big c;
	c.a[0]=max(p.a[0],q.a[0]);
	for(int i=1;i<=c.a[0];++i)
	{
		c.a[i]+=p.a[i]+q.a[i];
		c.a[i+1]+=c.a[i]/base;
		c.a[i]%=base;
	}
	if(c.a[c.a[0]+1]) ++c.a[0];
	return c;
}

Big operator - (const Big &p,const Big &q)
{
	Big c=p;
	for(int i=1;i<=c.a[0];++i)
	{
		c.a[i]-=q.a[i];
		if(c.a[i]<0) c.a[i]+=base,--c.a[i+1];
	}
	while(c.a[0]>0&&!c.a[c.a[0]]) --c.a[0];
	return c;
}

Big operator * (const Big &p,const Big &q)
{
	Big c;
	c.a[0]=p.a[0]+q.a[0]-1;
	for(int i=1;i<=p.a[0];++i)
	for(int j=1;j<=q.a[0];++j)
	{
		c.a[i+j-1]+=p.a[i]*q.a[j];
		c.a[i+j]+=c.a[i+j-1]/base;
		c.a[i+j-1]%=base;
	}
	if(c.a[c.a[0]+1]) ++c.a[0];
	return c;
}

Big operator / (const Big &p,const Big &q)
{
	Big x,y;
	for(int i=p.a[0];i>=1;--i)
	{
		y.add(p.a[i]);
		y.re();
		while(!(y<q))
			y=y-q,++x.a[i];
		y.re();
	}
	x.a[0]=p.a[0];
	while(x.a[0]>0&&!x.a[x.a[0]]) --x.a[0];
	return x;
}

char str1[MAXN],str2[MAXN];

int main()
{
	scanf("%s%s",str1,str2);
	Big a=Big(str1);
	Big b=Big(str2);
/*	Big c=a-b;
	c.print();	*/
/*	if(b<a)
	{
		Big c=a-b;
		c.print();
	}
	else 
	{
		Big c=b-a;
		if(c.a[0]) printf("-");
		c.print();		
	}*/
/*	Big c=a*b;
	c.print();*/
	Big c=a/b;
	c.print();
	return 0;
}

参考文献

hnqw1214 压位的高精度大数模板

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值