判断两个有符号数相乘是否会溢出
1.使用除法
/*Determine whether arguments can be multiplied without overflow */
int tmult_ok(int x, int y) {
int p = x*y;
/*Either x is zero ,or dividing p by x gives y*/
return !x || p/x == y;
}
2.不使用除法
typedef long int int64_t;
/*Determine whether arguments can be multiplied without overflow */
int tmult_ok(int x, int y) {
int64_t pll = (int64_t)x*y;
/*Either x is zero ,or dividing p by x gives y*/
return pll == (int)pll;
}