Project Euler 106 - Special Subset Sums: Meta-testing
Official link: https://projecteuler.net/problem=106
Problem is related to Problem 103 and Problem 105
Thought Process
Quite an easy problem. The hardest part for me was actually figuring out what the problem was asking!
It's quite obvious that we only would need to test subset B, C of the same size since otherwise condition 2tells us that they cannot be equal. Following my logic from Problem 103 and 105, I represent a subset of A using a bitmap, for example if A = [a, b, c, d], then [1, 0, 0, 1] := 1001 represents the subset {a, d}.
Now for the case n = 4 there are only 3 subset pairs of the same size we can compare:
0011 vs 1100:
Clearly 0011 > 1100 since we know by definition of A that d > b, c > a, which implies that d + c > a + b
0101 vs 1010
Clearly 1010 > 0101 since d > c, b > a, which implies that d + b > c + a
0110 vs 1001
This case we must manually test since d > c but b > a so it depends on if d - c > b - a
This is the one case we need to test!
I implore you to expand out the case for n = 5 but the idea should be clear now.
Simply compare 2 subsets B, C against each other and if the position of the highest 1-bit of B is bigger than the position of the highest 1-bit of C (that is for example d > b in case 1 above) then we need to check that this relation holds for every next 1-bit of B and C, if at some point the highest remaining bit of C is bigger than highest remaining bit of B then we get into the case where we can no longer be assured of which subset has a larger sum.
Interactive Code
Input an integer (yourinput)
Code will output for n = yourinput the number of subset pairs that need to be tested for equality