简体   繁体   中英

Big Integer Class C++

I'd like to write an unsigned Big Int library in C++ as an exercise, however I would like to stay away from using the traditional vector of chars storing individual digits. Due to the amount of memory wasted by this approach.

Would using a vector of unsigned short ints (ie. 16 bit postive integers) work, or is there a better way of doing this?

To Clarify, I would store "12345678" as {1234, 5678}.

Storing digits in corresponding char s is certainly not traditional, because of the reason you stated - it wastes memory. Using N-bit integers to store N corresponding bits is the usual approach. It wastes no memory, and is actually easier to implement (though harder to debug, because the integers are typically large).

Yes, using unsigned short int for individual units of information (generalized "digits") is a good idea. However, consider using 32-bit or 64-bit integers - they are closer to the size of the CPU registers, so your implementation will be more efficient.

General idea of syntax:

class BigInt
{
private:
    std::vector<uint64_t> digits;
};

You should decide whether you store least significant digits in smaller or larger indices. I think smaller is better (because addition, subtraction and multiplication algorithms start from LSB), but it's your choice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM