高精度算法模板

简单模拟就可以实现高精度加、减、乘、除(高精度除以低精度)

/*
* template:高精度算法
* date:2020/08/22
*/
#include<iostream>
#include<string>
using namespace std;
const int MAXLEN=1001;
typedef struct {
	int len;
	int num[MAXLEN];
} HugeInt;
bool negative;
//大数输入
HugeInt scanHugeInt() {
	string s;
	HugeInt hugeInt;
	cin>>s;
	hugeInt.len=s.size();
	for(int i=0; i<s.size(); i++) {
		hugeInt.num[hugeInt.len-i]=s[i]-'0';
	}
	return hugeInt;
}
//大数加法
HugeInt plusHugeInt(HugeInt a,HugeInt b) {
	int i;
	HugeInt res;
	res.len=a.len>b.len?a.len:b.len;
	for(i=1;i<=res.len;i++) res.num[i]=0;
	for(i=1; i<=res.len; i++) {
		res.num[i]+=a.num[i]+b.num[i];
		res.num[i+1]=res.num[i]/10;
		res.num[i]=res.num[i]%10;
	}
	return res;
}
//大数减法
HugeInt minusHugeInt(HugeInt a,HugeInt b) {
	int i;
	HugeInt res;
	negative=false;
	if(a.len<b.len) {
		negative=true;
	} else if(a.len==b.len) {
		for(i=1; i<=a.len; i++) {
			if(a.num[i]<b.num[i]) {
				negative=true;
				break;
			}
		}
	}
	if(negative) {
		HugeInt t=a;
		a=b;
		b=t;
	}
	res.len=a.len;
	for(i=1; i<=res.len; i++) {
		if(a.num[i]<b.num[i]) {
			a.num[i+1]--;
			a.num[i]+=10;
		}
		res.num[i]=a.num[i]-b.num[i];
	}
	while(res.num[res.len]==0&&res.len!=1) res.len--;
	return res;
}
//高精度乘法
HugeInt mutiplyHugeInt(HugeInt a,HugeInt b) {
	int i;
	int x;//进位
	HugeInt res;
	res.len=a.len+b.len;
	for(i=1; i<=res.len; i++) res.num[i];
	for(i=1; i<=a.len; i++) {
		x=0;
		for(int j=1; j<=b.len; j++) {
			res.num[i+j-1]+=a.num[i]*b.num[j]+x;
			x=res.num[i+j-1]/10;
			res.num[i+j-1]%=10;
		}
		res.num[i+b.len]=x;
	}
	while(res.num[res.len]==0&&res.len!=1) res.len--;
	return res;
}
//高精度除法(高精度除以低精度)
HugeInt divideSmallInt(HugeInt a,int b) {
	HugeInt res;
	int x;//余数
	res.len=a.len;
	x=0;
	for(int i=a.len; i>=1; i--) {
		res.num[i]=(a.num[i]+x*10)/b;
		x=(a.num[i]+x*10)%b;
	}
	while(res.num[res.len]==0&&res.len!=1) res.len--;
	return res;
}
int main() {
	HugeInt a=scanHugeInt();
	HugeInt b=scanHugeInt();;
	int c;
	cin>>c;
	HugeInt plus=plusHugeInt(a,b);
	HugeInt minus=minusHugeInt(a,b);
	HugeInt mutiply=mutiplyHugeInt(a,b);
	HugeInt divide=divideSmallInt(a,c);
	cout<<"plus:";
	int i;
	for(i=plus.len; i>=1; i--) cout<<plus.num[i];
	cout<<endl;
	cout<<"minus:";
	if(negative) cout<<"-";
	for(i=minus.len; i>=1; i--) cout<<minus.num[i];
	cout<<endl;
	cout<<"mutiply:";
	for(i=mutiply.len; i>=1; i--) cout<<mutiply.num[i];
	cout<<endl;
	cout<<"divide:";
	for(i=divide.len; i>=1; i--) cout<<divide.num[i];
	cout<<endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值