以uint为例,当计算过程中(比如9999^6)产生大于UINT_MAX(2^32 - 1)的值的时候,编译时会产生integer overflow,即数值溢出,最后的结果也被截断.
1.如何检测 :https://www.quora.com/How-do-I-prevent-integer-overflow-in-C++(有墙)
贴上里面提供的示例代码:
#include <iostream> #include <cstdlib> #include <climits> int main() { int x = 0x70000000; int y = 0x70000000; bool underflow = false; bool overflow = false; if ((x > 0) && (y > INT_MAX - x)) overflow = true; if ((x < 0) && (y < INT_MIN - x)) underflow = true; if(overflow) { std::cerr << "overflow will occur "; exit(-1); } if(underflow) { std::cerr << "underflow will occur "; exit(-1); } int z = x + y; // UH OH! std::cout << z << " "; }
2.如何解决:可以使用数组或者字符串模拟,例如使用std::string模拟乘法计算.只要内存够,多大的数都存的下(这里类似pure python的处理方式:使用pure python做运算,不会产生overflow,但是使用Numpy则会有overflow的问题,具体可参考:https://mortada.net/can-integer-operations-overflow-in-python.html)
string bigmul(string a, string b) { int size = a.size() + b.size(); char* res = new char[size]; memset(res, a.size() + b.size(), 0); for (int i = b.size() - 1; i >= 0; i--) { for (int j = a.size() - 1; j >= 0; j--) { res[i+j+1] += (b[i] - '0')* (a[j] - '0'); res[i+j] += res[i+j+1]/10; res[i+j+1] = res[i+j+1]%10; } } for (int i = 0; i < size; i++) { res[i] += '0'; } return res[0] == '0' ? string(res+1) : string(res); }