1
I’m making a dynamic numeric class, storing the value of the number in a vector of bytes. I did the functions of summation, subtraction and multiplication in the same way that we learn in school, but this cannot be applied in the division. What’s 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’ve done are the same as what you learn in school considering each uchar
vector as if it were a digit based on 256.
How the rest can be negative?
– Felipe Nascimento
Anyway, the division will be Euclidean integer, because this class has no signature and no decimal digits (floating point)
– Felipe Nascimento
The entire division in computation is different from the entire division in mathematics. If, for example, you write in C++ the constant expression ((-99)%(15)), the value of the expression will be -9 when in fact the rest of the Euclidean division returns 6 (15-9). It is because ((99)%(15)) is 9, then if the dividend (in case 99) changes signal, in computing the rest (in case 9) also exchange signal.
– RHER WOLF
What method do you recommend for step (1)? I’m new at this, I can only think of using one
for
or awhile
, but I will have with it 256 8-1 repetitions in the worst case (0xFFFFFFFFFFFFFFF / 1)– Felipe Nascimento
I will complement at the end of my reply.
– RHER WOLF