I am writing a class for large numbers up to 2 ^ 512. I’m using the unsigned __int64
array. The addition of numbers is inadequate, due to the variable c. The algorithm was taken from the book. Can you suggest a working algorithm?
class BigInt {
public:
unsigned __int64 number [8];
BigInt ()
{
for (int i = 0; i & lt; 8; i ++)
{
number [i] = 0;
}
}
const BigInt operator + (const BigInt & amp; rv) const
{
BigInt res;
unsigned __int64 c = 0, t = 0;
for (int i = 0; i & lt; 8; i ++)
{
t = number [i] + rv.number [i] + c;
c = t% LLONG_MAX;
res.number [i] = c;
}
res.number [7] = t;
return res;
}
};
Answer 1, authority 100%
There is absolutely no need to use the %
and /
operations. This is shooting sparrows with a cannon, not to mention the fact that such calculations must be performed in a type wider than your unsigned __int64
. And you don’t have this type at your disposal.
There is also no need to bind to a specific type through constants like LLONG_MAX
(and why is the signed maximum suddenly used?).
Remember that c
can only be 0
or 1
.
This is how it might look
BigInt operator + (const BigInt & amp; rv) const
{
BigInt res;
unsigned __int64 carry = 0;
for (int i = 0; i & lt; 8; i ++)
{
res.number [i] = number [i] + rv.number [i] + carry;
carry = carry? res.number [i] & lt; = number [i]: res.number [i] & lt; number [i];
}
return res;
}
Answer 2, authority 50%
There is at least one blunder in your code: instead of
c = t% LLONG_MAX;
res.number [i] = c;
needed
c = t / LLONG_MAX;
res.number [i] = t% LLONG_MAX;
Accordingly, the final res.number [7] = t;
is not needed.
In addition, the type t
must be wider than the type of number
elements.