I am doing a dynamic numeric class, storing the value of the number in a vector of bytes. I did the functions of addition, subtraction and multiplication in the same way that we learn in school, but this can not be applied in the division. What is the right way to do it?
typedef unsigned char uchar;
typedef unsigned short ushort;
typedef unsigned int uint;
typedef unsigned long ulong;
class Num
{
private:
vector<uchar> x;
...
public:
...
Num(vector<uchar> other)
{
if(other.size() > 8) other.resize(8);
while(!other.empty() && other[other.size() - 1] == 0)
other.pop_back();
x = other;
}
size_t size() const
{
return x.size();
}
...
friend Num operator+(Num l, const Num& rhs)
{
Num r = rhs;
vector<uchar> res (l.x);
vector<uchar> mod (1, 0);
while(r.size() < res.size()) r.x.push_back(0);
while(r.size() > res.size()) res.push_back(0);
for(uchar i = 0; i < res.size(); i++)
{
mod.push_back((ushort)res[i] + (ushort)r.x[i] > 0xff);
res[i] += r.x[i];
}
Num nmod = mod;
if(nmod.size() > 0) return (Num(res) + nmod);
return Num(res);
}
friend Num operator-(Num l, const Num& rhs)
{
Num r = rhs;
vector<uchar> res (l.x);
vector<uchar> mod (1, 0);
while(r.size() < res.size()) r.x.push_back(0);
while(r.size() > res.size()) res.push_back(0);
for(uchar i = 0; i < res.size(); i++)
{
mod.push_back(res[i] < r.x[i]);
res[i] -= r.x[i];
}
Num nmod = mod;
if(nmod.size() > 0) return (Num(res) - nmod);
return Num(res);
}
Num& operator+=(const Num& r)
{
Num res = *this + r;
*this = res;
return *this;
}
Num& operator-=(const Num& r)
{
Num res = *this - r;
*this = res;
return *this;
}
friend Num operator*(Num l, const Num& rhs)
{
Num r = rhs;
Num res;
for(uchar i = 0; i < r.size(); i++)
{
vector<uchar> temp(i, 0);
vector<uchar> mod(i + 1, 0);
for(uchar j = 0; j < l.size(); j++)
{
ushort v = l.x[j] * r.x[i];
temp.push_back(v % 256);
mod.push_back(v / 256);
}
res += Num(temp) + Num(mod);
}
return res;
}
...
};
The operations I did are the same as the ones that you learn in school, considering each% of the vector% as if it were a 256-based numeric.