这个条件是否足以满足乘法运算中的溢出检查 [英] does this condition suffice for overflow check in multiplication

查看:88
本文介绍了这个条件是否足以满足乘法运算中的溢出检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    int isOverflow(uint a, uint b) {
        // a and b are unsigned non-zero integers.
        uint c = a * b;

        if (c < ( a > b ? a : b))
                return 1;
        else
                return 0;
}

我想念什么吗?我认为上面的代码片段会起作用.

Am I missing something ? I think the above snippet will work.

编辑:我看过其他解决方案,例如

EDIT : I have seen other solutions like multiplication of large numbers, how to catch overflow which uses some fancy methods to check it. But to me above simple solution also looks correct. Thats why I am asking this question.

推荐答案

很容易通过发现异常来证明这是错误的:

It's easy to prove this is wrong by finding an exception:

请考虑以下两个8位无符号值:a = 0x1Fb = 0xF.

Consider these two 8-bit unsigned values: a = 0x1F and b = 0xF.

c = a * b
c = 0x1F * 0xF
c = 0xD1              (Overflow! The real answer is 0x1D1)

c < ( a > b ? a : b)
0xD1 < 0x1F           => False  (Wrong!)

正确的答案是此处.

这篇关于这个条件是否足以满足乘法运算中的溢出检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆