#include int safeAdd(int i, int j, bool& flag) { flag = true; // make sure this always has some value if(i < 0) { if(INT_MIN - i < j) { // no underflow return i + j; } } else { if(INT_MAX - i > j) { // no overflow return i + j; } } flag = false; return i; } int safeMul(int i, int j, bool& flag) { flag = true; // make sure this always has some value // make j non-negative if(j < 0) { j = -j; i = -i; } if(j == 0) { return 0; } else if(j == 1) { return i; } else { int big = safeAdd(i, i, flag); if(!flag) { return i; } big = safeMul(big, j/2, flag); if(!flag) { return i; } if(j%2) { // j is odd big = safeAdd(big, i, flag); if(!flag) { return i; } } return big; } }