0

Two 32 bit integer values A and B, are processed to give the 32 bit integers C and D as per the following rules. Which of the rule(s) is(are) reversible? i.e. is it possible to obtain A and B given c and D in all condition?

A. C = (int32)(A+B), D = (int32)(A-B)

B. C = (int32)(A+B), D= (int32)((A-B)>>1)

C. C = (int32)(A+B), D = B

D. C = (int32)(A+B), D = (int32)(A+2*B)

E. C = (int32)(A*B), D = (int32)(A/B)

A few questions about the integer arithmetic. Modular addition forms amathematical structure known as an abelian group. How about signed addition? It's also commutative (that’s where the “abelian” part comes in) and associative, is this forms a n an abelian group?

Given that integer addition is commutative and associative, C is apparently true, because we can retrieve A by (A+(B-B)). What about D? Can we assume that 2 * B = B + B st. B = A+B+B-(A+B)?

And multiplication is more complicated, but I know that it can not be retrieve A if there is an overflow.

4

1 回答 1

8

这是来自 5 [expr] 第 4 段的引述:

如果在计算表达式期间,结果未在数学上定义或不在其类型的可表示值范围内,则行为未定义。

使无符号整数溢出的原因在 3.9.1 [basic.fundamental] 第 4 段中定义:

无符号整数应遵守算术模 2 n的定律,其中 n 是该特定整数大小的值表示中的位数。

基本上,这表示在使用有符号整数算术时不会溢出。如果你这样做了,所有的赌注都没有了。这意味着有符号整数在 C++ 中不会形成阿贝尔群。

于 2013-10-06T03:46:40.717 回答