跳到正文

个人记录

高精度 v4.0

ckain约 5 分钟
原文
文章信息与版本

文章信息

发布
2022年9月23日
收录
2026年11月27日
更新
2026年11月27日
篇幅
约 5 分钟
获赞
2

版本

  1. v1当前

高精度 v4.0(基于高精度 v3.8 的改进版)
使用时可以稍微调低一点压位位数

C++
#include<bits/stdc++.h>
using namespace std;
const int Max=1e8,Mpow=4e3;
struct big{
	long long p, d[Mpow];
	big(int x=0){
		memset(d,0,sizeof(d)); p=1;
		if(!x) return;
		for(;x;x/=Max,p++) d[p]=x%Max; p--;
	}
	void in(){
		string s; cin>>s;
		int len=s.size();
		reverse(s.begin(),s.end()); s=' '+s;
		for(int i=1;i<=len;i++) s[i]-=48;
		
		for(int j=1,_pow=1; j<=len; j++){
			if(_pow==Max){_pow=1; p++;}
			d[p]+=s[j]*_pow; _pow*=10;
		}
	}
	void out(){
		printf("%lld",d[p]);
		for(int i=p-1;i;i--) printf("%08lld",d[i]);
	}
	
	bool operator ==(const big x)const{
		if(p!=x.p) return 0;
		for(int i=p;i;i--)
			if(d[i]!=x.d[i]) return 0;
		return 1;
	}
	bool operator <(const big x)const{
		if(p<x.p) return 1;
		if(p>x.p) return 0;
		for(int i=p;i;i--){
			if(d[i]<x.d[i]) return 1;
			if(d[i]>x.d[i]) return 0;
		}	return 0;
	}
	bool operator >(const big x)const{return !((*this)<x||(*this)==x);}
	bool operator <=(const big x)const{return !((*this)>x);}
	bool operator >=(const big x)const{return !((*this)<x);}
	
	void ch1(int pos){
		d[pos+1]+=d[pos]/Max; d[pos]%=Max;
	}
	void ch2(){
		while(!d[p] && p>1) --p;
	}
	
	big operator +(const big x)const{
		big re; re.p=max(p,x.p)+1;
		for(int i=1;i<=re.p;i++){
			re.d[i]+=d[i]+x.d[i];
			re.ch1(i);
		}	re.ch2();
		return re;
	}
	
	big operator *(const big x)const{
		big re; re.p=p+x.p;
		for(int i=1;i<=p;i++)
			for(int j=1;j<=x.p;j++){
				re.d[i+j-1]+=d[i]*x.d[j];
				re.ch1(i+j-1);
			}	re.ch2();
		return re;
	}
	
	big operator -(const big x)const{
		big re; re.p=p;
		for(int i=1;i<=re.p;i++){
			re.d[i]+=d[i]-x.d[i];
			if(re.d[i]<0){
				re.d[i]+=Max;
				re.d[i+1]-=1;
			}
		}	re.ch2();
		return re;
	}
	
	big operator <<(const int x)const{
		big re; re.p=p+x;
		for(int i=1;i<=p;i++) re.d[x+i]=d[i];
		return re;
	}
	
	big operator /(const big x)const{
		big re, tmp=(*this);
		if(tmp<x) return re;
		re.p=p-x.p+2;
		for(int pos=re.p;pos;pos--){
			int l=0, r=Max; big cut;
			while(l!=r-1){
				int mid=(l+r)/2;
				cut=(big(mid)<<(pos-1))*x;
				if(cut>tmp) r=mid;
				else l=mid;
			}
			cut=(big(l)<<(pos-1))*x;
			tmp=tmp-cut; re.d[pos]=l;
		}
		re.ch2();
		return re;
	}
	
	big operator +(const int x)const{return (*this)+big(x);}
	big operator -(const int x)const{return (*this)-big(x);}
	big operator *(const int x)const{return (*this)*big(x);}
	big operator /(const int x)const{return (*this)/big(x);}
};
signed main(){
	return 0;
}