无符号二进制算术:如何证明(a-b)²=(b-a)²?
Let's break this down clearly, starting with what we know about unsigned arithmetic and the given identity.
First, a quick recap: In unsigned integer arithmetic, all operations run modulo (2^w), where (w) is the bit width of the type (like 32 bits for a typical unsigned int). The given equation a - b == ~(b - a) + 1 is just restating a core unsigned arithmetic rule: the negation of a value (x) in unsigned terms is equivalent to ~x + 1 (this is the two's complement representation, which unsigned math uses implicitly when "negative" results trigger overflow).
Step 1: Rewrite the given identity in modular terms
The equation a - b == ~(b - a) + 1 translates directly to:
[a - b \equiv -(b - a) \pmod{2^w}]
Let’s simplify things by letting (D = a - b). This means:
[b - a \equiv -D \pmod{2^w}]
Step 2: Expand both sides of the target equation
We need to prove ((a - b) \times (a - b) = (b - a) \times (b - a)) in unsigned arithmetic. Substituting our definition of (D):
- Left-hand side (LHS): (D \times D = D^2)
- Right-hand side (RHS): ((-D) \times (-D))
Step 3: Apply basic integer multiplication properties
In standard integer math, multiplying two negative values gives a positive result: ((-D) \times (-D) = D^2). This holds even under modulo (2^w) — since (D^2) is the exact same integer in both cases, its remainder when divided by (2^w) will be identical.
Step 4: Verify with your concrete example
Let’s plug in your values to confirm:
- (a = 5), (b = 3)
- (a - b = 2), so LHS = (2 \times 2 = 4)
- In unsigned arithmetic, (b - a = 3 - 5) overflows. For a 3-bit unsigned type, this equals (6) (since (2^3 - 2 = 6)). RHS = (6 \times 6 = 36), and (36 \mod 8 = 4) — which matches the LHS exactly.
This confirms the equation holds both mathematically and with a real-world example.
内容的提问来源于stack exchange,提问作者tsybaya

