I'd like to write a deadsimple bignum class using a series of (unsigned) integers. I can loosely see how addition and subtraction would work, but division and multiplication is another story. I know 32-bit compilers can emuate 64-bit int's by splitting the int64 in two int32's. I'm looking for an efficient method to do that.
I'd like to have C++ code, not assembly. Speed is no primary concern, but the most efficient solution without assemble is always nice to have.
Perhaps this can serve as a starting point. It implements up to 2,048-bit unsigned integers, using a base-65,536 representation. This means each digit fits in 16 bits, and we can trivially detect overflow (even when multiplying) by simply using 32 bits for the results.
This is C code however, but should be trivial to port to C++, or just use as an inspiration. It's very much optimized for readability rather than speed since this is not exactly the kind of stuff I'm good at. :)
您最好看一下任意精度算术 ,它将解释比起您的代码正在运行的处理器,仿真更高精度处理器的过程背后的想法。
在C ++上购买一本精装书,叫做《 NUMERICAL REIPES》,您会在第20.6页的页面p916到p925上找到所需的内容。
What's wrong with just using long long
? That's guaranteed to be at least 64 bits. Otherwise, your Knuth (vol. 2) should provide the basic algorithms.
Use simple byte array. You can have size of integer whatever you want*. You just have to operate in binary and take endianess into consideration (your bits will be 7-6-5-4-3-2-1-0-15-14-13...)
*RAM is limited
对于任意大小,请尝试一下GMP ,如果由于某种原因您不能依靠编译器为您做这件事,那么它也可以在32位上用于64位数学运算。
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.