Чтобы еще больше расширить ответ Нильса Ричард Шропепель изобрел это.
http://www.inwap.com/pdp10/hbaker/hakmem/boolean.html#item23
ПУНКТ 23 (Schroeppel):
(A И B) + (A ИЛИ B) = A + B = (A XOR B) + 2 (A И B).
(A + B)/2 = ((A XOR B) + 2(A AND B))/2
= (A XOR B)/2 + (A AND B)
= (A XOR B)>>1 + (A AND B)
avg(x,y){return((x^y)>>1)+(x&y);}
(A AND B) + (A OR B) = A + B
, поскольку A AND B
дает сумму общих (между A и B) степеней двух, A OR B
дает и те общие, и те, которые нет, следовательно:
(A AND B) + (A OR B) =
(sum of shared powers of two) +
((sum of shared powers of two) + (sum of unshared powers of two)) =
(sum of shared powers of two) +
((sum of shared powers of two) + (sum of powers of two of A only) +
(sum of powers of two of B only)) =
((sum of shared powers of two) + (sum of powers of two of A only)) +
((sum of shared powers of two) + (sum of powers of two of B only))
= A + B.
A XOR B
дает карту тех битов, которые отличаются между A и B. Следовательно,
A XOR B = (sum of powers of two of A only) + (sum of powers of two of B only).
И, таким образом:
2(A AND B) + (A XOR B) =
((sum of shared powers of two) + (sum of powers of two of A only)) +
((sum of shared powers of two) + (sum of powers of two of B only))
= A + B.