Simple bigint Class

 

To sunny: this is my simple bigint class written in C++, and I believe it is enough for many problems!

+ Defining the maximum number of digits lets the code very simple.

+ Long division is rarely used in programming contest, so I havenít coded it yet!

 

Download

 

#include <iostream.h>

#include <conio.h>

 

// Maximum number of digits

#define M 100

 

class bigint

{

††††† private:

††††††††††† int d[M];

††††† public:

††††††††††† bigint();

††††††††††† bigint(int); //construct from an integer

 

††††††††††† int operator < (bigint);

††††††††††† int operator == (bigint);

 

††††††††††† bigint operator + (bigint);

††††††††††† bigint operator - (bigint);

 

††††††††††† bigint operator * (int); // multiply by an integer

 

††††††††††† void print(ostream&); // print to the stream

};

 

bigint::bigint()

{

††††† for (int i=0; i<M; i++) d[i]=0;

}

 

bigint::bigint(int n)

{

††††† for (int i=M-1; i>=0; i--)

††††† {

††††††††††† d[i]=n%10;

††††††††††† n/=10;

††††† }

}

 

int bigint::operator < (bigint a)

{

††††† for (int i=0; i<M; i++)

††††† if (d[i] < a.d[i])

††††††††††† return 1;

††††† else if (d[i] > a.d[i])

††††††††††† return 0;

††††† return 0;

}

 

int bigint::operator == (bigint a)

{

††††† for (int i=0; i<M; i++)

††††† if (d[i] != a.d[i])

††††††††††† return 0;

††††† return 1;

}

 

bigint bigint::operator * (int n)

{

††††† int c=0;

††††† bigint a;

††††† for (int i=M-1; i>=0; i--)

††††† {

††††††††††† a.d[i]=d[i] * n + c;

††††††††††† c=a.d[i] / 10;

††††††††††† a.d[i]%=10;

††††† }

††††† return a;

}

 

bigint bigint::operator + (bigint a)

{

††††† int c=0;

††††† bigint b;

††††† for (int i=M-1; i>=0; i--)

††††† {

††††††††††† b.d[i]=d[i] + a.d[i] + c;

††††††††††† c=b.d[i] / 10;

††††††††††† b.d[i]%=10;

††††† }

††††† return b;

}

 

bigint bigint::operator - (bigint a)

{

††††† int c=0;

††††† bigint b;

††††† for (int i=M-1; i>=0; i--)

††††† {

††††††††††† b.d[i]=d[i] - a.d[i] - c;

††††††††††† if (b.d[i] < 0)

††††††††††† {

††††††††††††††††† b.d[i]+=10;

††††††††††††††††† c=1;

††††††††††† }

††††††††††† else c = 0;

††††† }

††††† return b;

}

 

void bigint::print(ostream &out)

{

††††† for (int i=0; i<M, d[i]==0; i++);

††††† if (i<M)

††††††††††† for (; i<M; i++)

††††††††††††††††† out << d[i];

††††† else

††††††††††† out << 0;

}

 

ostream & operator << (ostream &out, bigint a)

{

††††† a.print(out);

††††† return out;

}

 

// Testing the class

 

int main()

{

††††† clrscr();

 

††††† bigint a(12345);

††††† bigint b(23456);

††††† bigint c = a + b; // 35801

††††† bigint d = c - b; // 12345

 

††††† cout << c << endl;

††††† cout << d << endl;

††††† cout << c * 99 << endl;

††††† cout << c * 99 * 99 * 99 * 99 * 99 * 99 * 99 << endl;

††††† cout << ((c*99)==3544299) << endl;

††††† cout << ((c*99) < 3544298) << endl;

††††† cout << ((c*99) < 20000000);

 

††††† return 0;

}