"""EBM-0001: reproduce the finite margin certificate for L(3937)=35.
Python 3, standard library only. Run: python3 EBM-0001_grid_verify.py
"""
from itertools import product


def margins(p, q):
    """Reflection-symmetric p margins, each between 0 and q."""
    modulus = 2**p - 1
    weights = [2**j + 2**(p-j) for j in range(1, (p+1)//2)]
    out = {}
    for tail in product(range(q+1), repeat=len(weights)):
        a0 = -sum(a*w for a, w in zip(tail, weights)) % modulus
        if a0 > q:
            continue
        row = (a0,) + tail + tail[::-1]
        assert sum(a*2**j for j, a in enumerate(row)) % modulus == 0
        out.setdefault(sum(row), []).append(row)
    return out


rows = margins(5, 7)
cols = margins(7, 5)
print('Row totals:', sorted(rows))
print('Column totals:', sorted(cols))
common = set(rows) & set(cols)
assert common == {0, 17, 18, 35}
for total in (17, 18):
    print(f'Total {total}: rows {rows[total]}; columns {cols[total]}')
    for r, c in product(rows[total], cols[total]):
        assert max(r) > sum(x > 0 for x in c), (r, c)
assert (2**35-1) % 3937 == 0
print('All nontrivial common totals excluded. L(3937) = 35.')
