Home c++ Implementation of a class of large numbers with long arithmetic

Implementation of a class of large numbers with long arithmetic

Author

Date

Category

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.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions