C++高精度模板

#define rg register
const int maxn=2005,bas=10000;
struct jie{
	int num[maxn],len;
	bool jud;
	jie(){
		memset(num,0,sizeof(num));
		len=jud=0;
	}
	friend bool operator <(const jie& A,const jie& B){
		if(A.len<B.len) return 1;
		else if(A.len>B.len) return 0;
		for(rg int i=A.len;i>=1;i--){
			if(A.num[i]<B.num[i]) return 1;
			else if(A.num[i]>B.num[i]) return 0;
		}
		return 0;
	}
	friend jie operator + (const jie& A,const jie& B){
		rg jie C;
		C.len=std::max(A.len,B.len);
		for(rg int i=1;i<=C.len;i++){
			C.num[i]+=A.num[i]+B.num[i];
			if(C.num[i]>=bas){
				C.num[i]-=bas;
				C.num[i+1]++;
			}
		}
		if(C.num[C.len+1]) C.len++;
		return C;
	}
	friend jie operator -(const jie& A,const jie& B) {
		rg jie C;
		int js[maxn];
		if(A<B){
			C.len=B.len;
			for(rg int i=1;i<=C.len;i++){
				if(B.num[i]+js[i]>=A.num[i]){
					C.num[i]=B.num[i]+js[i]-A.num[i];
				} else {
					C.num[i]=B.num[i]+js[i]-A.num[i]+bas;
					js[i+1]-=1;
				}
			}
			C.jud=1;
		} else {
			C.len=A.len;
			for(rg int i=1;i<=C.len;i++){
				if(A.num[i]+js[i]>=B.num[i]){
					C.num[i]=A.num[i]+js[i]-B.num[i];
				} else {
					C.num[i]=A.num[i]+js[i]-B.num[i]+bas;
					js[i+1]-=1;
				}
			}
			C.jud=0;
		}
		while(!C.num[C.len]) C.len--;
		return C;
	}
	friend jie operator * (const jie& A,const jie& B){
		rg jie C;
		C.len=A.len+B.len;
		for(rg int i=1;i<=A.len;i++){
			for(rg intj=1;j<=B.len;j++){
				C.num[i+j-1]+=A.num[i]*B.num[j];
				if(C.num[i+j-1]>=bas){
					C.num[i+j]+=C.num[i+j-1]/bas;
					C.num[i+j-1]%=bas;
				}
			}
		}
		if(!C.num[C.len]) C.len--;
		return C;
	}
	friend jie operator /(const jie &A,const int &B){
		rg jie C;
		C.len=A.len;
		rg long long nans=0;
		for(rg int i=A.len;i>=1;i--){
			nans=nans*bas+A.num[i];
			if(nans>=B){
				C.num[i]=nans/B;
				nans%=B;
			}
		}
		while(!C.num[C.len]) C.len--;
		return C;
	}
	friend int operator %(const jie &A,const int &B){
		rg long long nans=0;
		for(rg int i=A.len;i>=1;i--){
			nans=nans*bas+A.num[i];
			if(nans>=B) nans%=B;
		}
		return nans;
	}
	void read(rg int val){
		len=0,jud=0,memset(num,0,sizeof(num));
		while(val){
			num[++len]=val%bas;
			val/=bas;
		}
	}
	void autoread(){
		char s[maxn];
		scanf("%s",s+4);
		rg int len2=strlen(s+4);
		s[0]=s[1]=s[2]=s[3]='0';
		len=0;
		for(rg int i=len2+3;i>=4;i-=4){
			num[++len]=(s[i-3]-'0')*1000+(s[i-2]-'0')*100+(s[i-1]-'0')*10+s[i]-'0';
		}
		while(!num[len] && len) len--;
	}
	void write(){
		if(len && jud) printf("-");
		if(!len) printf("0\n");
		if(len) printf("%d",num[len]);
		for(rg int i=len-1;i>=1;i--){
			printf("%04d",num[i]);
		}
		printf("\n");
	}
};
posted @ 2020-06-27 14:01  liuchanglc  阅读(388)  评论(0编辑  收藏  举报