Question

Wrote a header named big number that store big numbers as a string and do all mathematical operations on it but I can't override the operator / in a good and fast way, please help me on it.

class BigNumber
{
string Number;
bool Sign;
bool TheValueIsSet;
bool IsZero();

BigNumber MultipyWithMinus();
BigNumber WithOutSign();
BigNumber& MakeSimple();

BigNumber operator *(int);
public:
//Ctors
BigNumber();
BigNumber(const string&);
BigNumber(const BigNumber&);
BigNumber(const int);

//Operators
int operator[](int);
BigNumber operator ()(int i,int j);

BigNumber& operator =(BigNumber&);
BigNumber& operator =(int);
BigNumber& operator =(string&);
BigNumber& operator =(const char*);

BigNumber operator +(BigNumber&);
BigNumber operator -(BigNumber&);
BigNumber operator *(BigNumber&);
BigNumber operator /(BigNumber&);
BigNumber operator %(BigNumber&);

BigNumber& operator +=(BigNumber&);
BigNumber& operator -=(BigNumber&);
BigNumber& operator *=(BigNumber&);
BigNumber& operator /=(BigNumber&);
BigNumber& operator %=(BigNumber&);

BigNumber operator ++(int);
BigNumber& operator ++();
BigNumber operator --(int);
BigNumber& operator --();


bool operator ==(BigNumber&);
bool operator >(BigNumber&);
bool operator >=(BigNumber&);
bool operator <=(BigNumber&);
bool operator <(BigNumber&);
bool operator !=(BigNumber&);

//Functions
string ToString();
bool IsNegative();
};

BigNumber BigNumber::operator /(BigNumber& Second)
{
      //what I must write here ?
}

can we do the divide operation just with the Bitwise operators ?

Was it helpful?

Solution

Just so we talk the same language:

  • quotient = result of divide
  • dividend = the number being divided
  • divisor = the number you divide by

In other words: quotient = dividend/divisor;

I'm assuming you are doing integer math - the principle is pretty much the same if you have a decimal point, but you have to "slide" the decimal point along when you follow these steps.

The general principle for stringwise divide is:

  1. initialize temp quotient = 1
  2. initialize final quotient = 0

  3. Multiply the divisor by 10 until it's length is equal to the dividend

    • /* multiply by 10 = insert zero at end of string */
    • at the same time, multiply the temp quotient by 10.
  4. if divisor > dividend, divide temp quotient and divisor by 10.

  5. as long as divisor < dividend

    • subtract divisor from dividend
    • add temp quotient to final quotient.
  6. If dividend > 0, go to 4.

This is clearly not the most efficient method, but it's fairly simple, but it's not the worst either (that would be to subtract divisor as many times as you can from the dividend, and 1000000000 / 1 would take 1000000000 iterations - really large numbers would take "forever").

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top