1. 程式人生 > 實用技巧 >高精度運算

高精度運算

包含了 加、減、乘、除(低精

// sad
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>

using namespace std;

template<typename _T>
void read(_T &x)
{
	x=0;char s=getchar();int f=1;
	while('9'<s||s<'0'){f=1;if(s=='-')f=-1;s=getchar();}
	while('0'<=s&&s<='9'){x=(x<<3)+(x<<1)+s-'0';s=getchar();}
	x*=f;
}
int n,m,k,p;
char c[10005];

struct bignum{
	int z[90005];
	int cnt;
	
	void init()
	{
		memset(z,0,sizeof(z));
		cnt = 0;
	}
	
	void read()
	{
		scanf("%s",c+1);
		
		cnt = strlen(c+1);
		if(c[1] == '-')
		{
			z[0] = -1;
			for(int i=1;i<cnt;i++)
			c[i] = c[i+1];
			cnt--;
		}
		else z[0] = 1; 
		
		for(int i=1;i<=cnt;i++)
		{
			z[cnt - i + 1] = c[i]-'0';
		}
		
	}
	
	void print()
	{
		if(z[0] == -1) putchar('-');
		for(int i=cnt;i>=1;i--)
		putchar('0'+z[i]);
	}
};

bignum operator+(const bignum &a,const bignum &b)
{
	bignum c;
	c.init();
	int l1 = a.cnt;
	int l2 = b.cnt;
	int itn = max(l1,l2);
	c.cnt = itn;
	int x= 0;		
	for(int i=1;i<=itn ;i++)
	{
		c.z[i] = a.z[i] + b.z[i] + x;
		x = c.z[i]/10;
		c.z[i] %= 10;
	}
	if(x)
	{
		c.cnt++;
		c.z[c.cnt] = x;
	}	
	return c;
}

bignum operator*(const bignum &a,const bignum &b)
{
	bignum c;
	c.init();
	int l1 = a.cnt;
	int l2 = b.cnt;
	c.cnt = l1+l2-1;
	c.z[0] = a.z[0]*b.z[0];
	for(int i=1,x= 0;i<=l1;i++,x=0)
	{
		
		for(int j=1;j<=l2;j++)
		{
			c.z[i+j-1]+=a.z[i] * b.z[j]+x;
			x = c.z[i+j-1]/10;
			c.z[i+j-1]%=10;
		}
		if(x)
		{
			c.z[i+l2] = x%10;
			c.cnt = max(c.cnt , i+l2);
			x/=10;
		}	
	}
	
	while(!c.z[c.cnt] && c.cnt >1) c.cnt--;
	return c;
}

bignum operator/(bignum a , int b)
{
	bignum c;
	c.init();
	c.cnt = a.cnt;
	
	int x=0;
	
	for(int i=a.cnt;i>=1;i--)
	{
		x = x*10+a.z[i];
		c.z[i] = x/b;
		x%=b;
	}
	
	while(c.cnt>1 && !c.z[c.cnt]) c.cnt--;
	
	return c;
}

bool operator<(const bignum &a,const bignum &b)
{
	if(a.z[0]*b.z[0]<0)
	{
		if(a.z[0] == 1) return 0;
		else return 1;
	}
	else
	{
		int key = a.z[0];
		
		if(a.cnt > b.cnt) return key>0?0:1;
		if(a.cnt < b.cnt) return key>0?1:0;
		
		for(int i=a.cnt;i>=1;i--)
		{
			if(a.z[i] > b.z[i]) return key>0?0:1;
			if(a.z[i] < b.z[i]) return key>0?1:0;
		}
		
		return 0;
	}
}

bignum operator-(const bignum &a , const bignum &b)
{
	bignum c;
	c.init();
	int l1 = a.cnt;
	int l2 = b.cnt;
	
	c.cnt = max(l1,l2);
	c.z[0] = (a<b)?-1:1;
	
	if(c.z[0] == 1)
	{
		int x=0;
		for(int i=1;i<=l1;i++)
		{
			c.z[i] = a.z[i] - b.z[i]-x;
			if(c.z[i]<0)
			c.z[i]+=10,x=1;
			else x= 0;
		}
		while(c.cnt>1 && c.z[c.cnt]==0){c.cnt--;}
	}
	else
	{
		int x=0;
		for(int i=1;i<=l2;i++)
		{
			c.z[i] = b.z[i] - a.z[i]-x;
			if(c.z[i]<0)
			c.z[i]+=10,x=1;
			else x= 0;
		}
		while(c.cnt>1 && !c.z[c.cnt]){c.cnt--;}		
	}
		
	return c;
}

signed main()
{
	ios_base::sync_with_stdio(false);
	cout.tie(NULL);
	cin.tie(NULL);
	
	bignum a;
	int b;
	
	a.init();
	a.read();
	read(b);
	bignum c;
	
	c.init();
	c = a/b;
	
	c.print();
	

}