Java教程

高精度模板

本文主要是介绍高精度模板,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

NOI大肛说:高精+ - × ÷(高精除单精) %(高精模单精)

以下是模板:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<string>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#include<iomanip>

using namespace std;
char in1[10010],in2[10010];
long long in3;

struct num{
	long long l[7000];
	bool k;
}i1,i2;

long long read(){
	long long x=0,h=1;char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')h=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){x=x*10+(long long)(ch-'0');ch=getchar();}
	return x*h;
}

bool operator < (num a,num b){
	if(a.l[0]!=b.l[0])return a.l[0]<b.l[0];
	for(long long i=a.l[0];i>=1;i--)
		if(a.l[i]!=b.l[i])return a.l[i]<b.l[i];
	return 0;
}

num operator - (num a,num b){
	num c;
	
	// check '<0'
	if(a<b){
		swap(a,b);c.k=1;
	}
	
	// clear
	memset(c.l,0,sizeof(c.l));
	
	// calc
	c.l[0]=max(a.l[0],b.l[0]);
	for(long long i=1;i<=c.l[0];i++){
		c.l[i]=a.l[i]-b.l[i];
		if(c.l[i]<0)c.l[i]+=10,a.l[i+1]--;
	}
	c.l[0]++;
	while(c.l[--c.l[0]]==0&&c.l[0]>1){}
	
	return c;
}

num operator + (num a,num b){
	num c;
	
	// clear
	c.k=0;
	memset(c.l,0,sizeof(c.l));
	
	// calc
	c.l[0]=max(a.l[0],b.l[0])+2;
	for(long long i=1;i<=c.l[0];i++){
		c.l[i]+=a.l[i]+b.l[i];
		c.l[i+1]+=(c.l[i]/10);
		c.l[i]%=10;
	}
	c.l[0]++;
	while(c.l[--c.l[0]]==0&&c.l[0]>1){}
	
	return c;
}

num operator * (num a,num b){
	num c;
	
	// clear
	c.k=0;memset(c.l,0,sizeof(c));
	
	// calc
	c.l[0]=a.l[0]+b.l[0]+2;
	for(long long i=1;i<=a.l[0];i++){
		for(long long j=1;j<=b.l[0];j++){
			c.l[i+j-1]+=(a.l[i]*b.l[j]);
		}
	}
	for(long long i=1;i<=c.l[0];i++)c.l[i+1]+=(c.l[i]/10),c.l[i]%=10;
	
	c.l[0]++;
	while(c.l[--c.l[0]]==0&&c.l[0]>1){}
	return c;
}

num operator / (num a,long long b){
	num c;
	
	// clear
	c.k=0;memset(c.l,0,sizeof(c.l));
	
	// calc
	long long sum=0;
	for(long long i=a.l[0];i>=1;i--){
		sum=sum*10+a.l[i];
		c.l[i]=sum/b;
		sum=sum%b;
	}
	c.l[0]=a.l[0];
	
	c.l[0]++;
	while(c.l[--c.l[0]]==0&&c.l[0]>1){}
	return c;
}

long long operator % (num a,long long b){
	num c;
	
	// clear
	c.k=0;memset(c.l,0,sizeof(c.l));
	
	// calc
	long long sum=0;
	for(long long i=a.l[0];i>=1;i--){
		sum=sum*10+a.l[i];
		c.l[i]=sum/b;
		sum=sum%b;
	}
	c.l[0]=a.l[0];
	
	c.l[0]++;
	while(c.l[--c.l[0]]==0&&c.l[0]>1){}
	return sum;
}

void print(num a){
	if(a.k)putchar('-');
	
	for(long long i=a.l[0];i>=1;i--)putchar(a.l[i]+'0');
	
	return ;
}

int main(){
	
	// read and transform
	scanf("%s",in1+1);
	scanf("%s",in2+1);
	cin>>in3;
	in1[0]=in2[0]='?';
	
	i1.l[0]=strlen(in1)-1;
	i2.l[0]=strlen(in2)-1;
	
	for(long long i=1;i<=i1.l[0];i++)i1.l[i]=in1[i1.l[0]-i+1]-'0';
	for(long long i=1;i<=i2.l[0];i++)i2.l[i]=in2[i2.l[0]-i+1]-'0';
	

应该注意以下几点:

  • c.l[0]++; while(c.l[--c.l[0]]==0&&c.l[0]>1){}中:
    • c.l[0]++; 是很有必要的,因为在之后的第一次判断中,c.l[0]会直接减一,不会对c.l[0]进行判断
    • c.l[0]>1 可以防止数字为0。
这篇关于高精度模板的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!