高精度算法库

  初始化:bign a=2,b = 1335235235,c = "-4335";

  支持+,-,*,/运算,已经重载运算符,可以直接a+b,a-b,a*b,a/b,但不可以a+2,a+b+c。支持标准输入输出流输出。

  支持比较 < <= > >= == !=,支持位移<< >>(以10为单位),支持取反 !

/*
 * bign.cpp
 * 高精度算法库
 */

#include 
#include 
using namespace std;

#define MAXN 1000

struct bign
{
	int len;
	bool f;
	short s[MAXN];

	/* 构造函数 */
	bign()
	{
		memset(s,0,sizeof(s));
		f = false;	
		len = 0;
	}
	bign(const char* num){ *this = num; }
	bign(int num){ *this = num; }
	bign(long num){ *this = num; }
	bign(long long num){ *this = num; }
	bign(const bign &a)
	{
		len = a.len;
		f = a.f;
		for(int i=0;i 0)
			{
				arr[j++] = '0' + s[len-i-1];
			}			
			else
			{
				arr[j] = '\0';
				break;
			}
		}
	}
		
	bool cmp(bign* a,bign* b)
	{
		if(a->len != b->len) return a->lenlen;
		for(int i=a->len-1;i>=0;i--)
			if(a->s[i] != b->s[i]) return a->s[i] < b->s[i];
		return false;
	}

	bool operator < (bign& b)
	{
		if(f && !b.f) 			return true;			// a<0,b>0 ---> a0,b<0 ---> !a !|a|<|b|
		else					return	cmp(this,&b);	// a>0,b>0 ---> |a|<|b|
	}
	bool operator > (bign& b) { return b<*this; }
	bool operator <= (bign& b) { return !(b<*this); }
	bool operator >= (bign& b) { return !(*this < b); }
	bool operator != (bign& b) { return (b < *this) || (*this < b); }
	bool operator == (bign& b) { return !(*this != b); }

	bign operator !() { bign a = *this; a.f = !a.f; return a;}
	// 加法函数,纯绝对值相加
	bign add(bign& a,bign& b)
	{
		bign c;
		c.len = 0;
		int maxlen = max(a.len,b.len);
		int i=0,g=0;

		for(i=0,g=0;g || i0)
			c.s[--k] = s[--j];

		return c;
	}
	bign operator >> (unsigned int i)
	{
		bign c;
		c.len = len-i>=0 ? len-i : 0;

		int k=0,j=i;
		while(kf && !b.f) || (!this->f && b.f))		
		{
			if(cmp(&b,this))
			{
				c = minus(*this,b);
				c.f = this->f;
			}
			else
			{
				c = minus(b,*this);
				c.f = b.f;
			}
		}
		/* 两个正数绝对值相加,或两个正数绝对值相加 */
		else
		{
			c = add(*this,b);
			c.f = this->f;
		}
		
		return c;
	}

	bign operator - (bign& b)
	{
		b.f = !b.f;
		bign c = *this + b;
		b.f = !b.f;

		return c;
	}		


	bign operator * (bign& b)
	{
		int i,j;
		bign c;
		c.f = (f != b.f);					// 同号得正,异号得负

		for(i=0;i= 10)
		{
			c.s[c.len++] = c.s[i+j+1]%10;
			c.s[i+j+1] %= 10;			
		}

		return c;
	}				


	
	bign operator / (bign&b)
	{
		int i,j;
		bign c;
		bign a = *this;

		c.f = (a.f != b.f);					// 同号得正,异号得负

		for(i=a.len-b.len;i>=0;i--)			// 被除数前面至少有除数的位数
		{
			bign try_num;
			bign bb = b<> (istream &in,bign &x)
{
	char s[MAXN];
	in>>s;
	x = s;
	return in;
}
	
ostream& operator << (ostream &out,bign &x)
{
	char s[MAXN];
	x.str(s,MAXN);
	out<


你可能感兴趣的:(数论)