"""Exact certificate for the proposed OEIS A016729 term at a multiple of six.

Run: python verify.py
No libraries are needed beyond the Python standard library.
"""
from fractions import Fraction
from math import comb


def tail_coefficient(m, j):
    """Coefficient in the full inverse-series expansion, j=m+1 or m+2."""
    e = 3 * j - 3 * m - 1
    convolution = sum(comb(e, r) * 3**r * comb(3*j-2-r, j-1-r)
                      for r in range(min(e, j-1) + 1))
    return Fraction(-9*m*convolution, j)


def first_negative(m):
    c, d = tail_coefficient(m, m+1), tail_coefficient(m, m+2)
    return (2*m + 11) * c - d


def direct_basis_check(m):
    """Cancel the first m coefficients using only binomial products."""
    deg = m + 2
    accum = [0] * (deg + 1)
    for j in range(m + 1):
        coeff = 1 if j == 0 else -accum[j]
        a, b = 3*(m-j), 2*j
        for t in range(deg - j + 1):
            conv = sum(comb(a, t-r) * 3**(t-r) * comb(b, r) * (-1)**r
                       for r in range(max(0, t-a), min(b, t)+1))
            accum[t+j] += coeff * conv
    assert accum[0] == 1 and all(v == 0 for v in accum[1:m+1])
    return accum[-1]


if __name__ == '__main__':
    m = next(m for m in range(1, 2001) if first_negative(m) < 0)
    count = direct_basis_check(m)
    assert count == first_negative(m) and count < 0
    print('m, length, predicted distance, impossible weight, count:')
    print(m, 6*m, 2*m+2, 2*m+4, count)
