The Problem:
In a magic rectangle of dimensions m x n, every entry is the XOR of the row and column, zero-indexed. Example (8 x 5):
0 1 2 3 4 5 6 7
1 0 3 2 5 4 7 6
2 3 0 1 6 7 4 5
3 2 1 0 7 6 5 4
4 5 6 7 0 1 2 3
I need to find the sum of every entry, however, brute-forcing will not work as inputs range in the 10s of millions.
My work so far:
I found, that for a m x n matrix where the m or n is a power of 2, you can calculate the sum as sum_range(0, m-1) * n, where sum range literally just adds every number between the first and second input.
Things get interesting when neither m nor n is a power of 2.
You can split the m x n rectangle into a rectangle composed of sub m x n rectangles that are powers of two, like this: (15 x 15)
0, 1, 2, 3, 4, 5, 6, 7 | 8, 9, 10, 11 | 12, 13 | 14 |
1, 0, 3, 2, 5, 4, 7, 6 | 9, 8, 11, 10 | 13, 12 | 15 |
2, 3, 0, 1, 6, 7, 4, 5 | 10, 11, 8, 9 | 14, 15 | 12 |
3, 2, 1, 0, 7, 6, 5, 4 | 11, 10, 9, 8 | 15, 14 | 13 |
4, 5, 6, 7, 0, 1, 2, 3 | 12, 13, 14, 15 | 8, 9 | 10 |
5, 4, 7, 6, 1, 0, 3, 2 | 13, 12, 15, 14 | 9, 8 | 11 |
6, 7, 4, 5, 2, 3, 0, 1 | 14, 15, 12, 13 | 10, 11 | 8 |
7, 6, 5, 4, 3, 2, 1, 0 | 15, 14, 13, 12 | 11, 10 | 9 |
----------------------------------------------------
8, 9, 10, 11, 12, 13, 14, 15 | 0, 1, 2, 3 | 4, 5 | 6 |
9, 8, 11, 10, 13, 12, 15, 14 | 1, 0, 3, 2 | 5, 4 | 7 |
10, 11, 8, 9, 14, 15, 12, 13 | 2, 3, 0, 1 | 6, 7 | 4 |
11, 10, 9, 8, 15, 14, 13, 12 | 3, 2, 1, 0 | 7, 6 | 5 |
----------------------------------------------------
12, 13, 14, 15, 8, 9, 10, 11 | 4, 5, 6, 7 | 0, 1 | 2 |
13, 12, 15, 14, 9, 8, 11, 10 | 5, 4, 7, 6 | 1, 0 | 3 |
----------------------------------------------------
14, 15, 12, 13, 10, 11, 8, 9 | 6, 7, 4, 5 | 2, 3 | 0 |
----------------------------------------------------
Then, using the formula I described above, you can get the sum of each of the squares along the diagonal (my explanation makes no sense so here is a picture): not enough reputation for embeds ._.
And that's were I am
I don't understand how to get the sum of the other parts, in terms of m and n, without brute-forcing. remember, m and n will be random integers, and they could be very very large
I see some pattern, like how the magic rectangle has some symmetry, and that the sides are the numbers 0 - (m-1) in order, however, I fail to come up with logic to translate that into code.
Pointers in the right direction would be appreciated. Not, however, looking for code, as this is a code wars problem and that's cheating
Reference Problem: https://www.codewars.com/kata/59568be9cc15b57637000054/train/java