2 ms·
The first one is already explained, a^b + 2*(a&b) is computing the sum and carry in parallel, and then adding them up. The second formula is more elaborate, an
by pbsd 4y ago
The first one is already explained, a^b + 2*(a&b) is computing the sum and carry in parallel, and then adding them up.
The second formula is more elaborate, and makes heavy use of the above identity:
2*(a|b)-(a^b)
= 2*((a&b)^a^b)-(a^b) (express boolean or in terms of and and xor)
= 2*(a&b) ^ 2*(a^b) - (a^b)
= 2*(a&b) + 2*(a^b) - (a^b) (there can't be carries, so xor equals addition in this case)
= 2*(a^b) + 4*(a&b) - 2*(a&b) - (a^b)
= 2*((a^b) + 2*(a&b)) - 2*(a&b) - (a^b)
= 2*(a+b) - (a+b)
= a+b.
- deleted 4y ago[deleted]