a AND b
are the bits that are in both of the numbers. So these are doubled in the sum. a XOR b
are the bits that are only present in one of the numbers so these should only be counted once in the sum.
Here is an example:
a = 4 = 1*2^2 + 0*2^1 + 0*2^0 (or just 100)
b = 13 = 1*2^3 + 1*2^2 + 0*2^1 + 1*2^0 (or just 1101)
a + b = (1*2^2 + 0*2^1 + 0*2^0) + (1*2^3 + 1*2^2 + 0*2^1 + 1*2^0) = 1*2^3 + 2*2^2 + 0*2^1 + 1*2^0
Note on the last line how the bit that is in both the numbers (2^2
) is counted twice in the sum while the rest are only counted once!
To solve your problem you need to find all pairs (a, b) that adds up to the sum. What you want to do is this:
- Subtract the XOR value from the SUM. You are left with
2*(a AND b)
. - Divide by 2. You now have all the bits that should be set in both a and b.
- Since you have the XOR value you know exactly what bits should be set in exactly one of a and b, while the AND value you just calculated are the bits that should be set in both of them. So you list all permutations of setting the bits in a or b respectively.
To continue my previous example:
a AND b = 0100
(set in both always)a XOR b = 1001
(we need to try all permutations of these)
We get these permutations as solution:
a = 0100 + 0000 = 0100, b = 0100 + 1001 = 1101 => (4, 13)
a = 0100 + 0001 = 0101, b = 0100 + 1000 = 1100 => (5, 12)
a = 0100 + 1000 = 1100, b = 0100 + 0001 = 0101 => (12, 5)
a = 0100 + 1001 = 1101, b = 0100 + 0000 = 0100 => (13, 4)