"""Exact checks for the Apéry Hankel determinants followed by numerical displays."""
from argparse import ArgumentParser
from decimal import Decimal, localcontext
from math import factorial


def choose(n, k):
    return factorial(n) // (factorial(k) * factorial(n - k))


def apery_terms(last):
    a = [1, 5]
    for k in range(1, last):
        numerator = (34*k**3 + 51*k*k + 27*k + 5)*a[-1] - k**3*a[-2]
        value, remainder = divmod(numerator, (k + 1)**3)
        assert not remainder
        a.append(value)
    for n, value in enumerate(a):
        assert sum((choose(n, k)*choose(n + k, k))**2 for k in range(n + 1)) == value
    return a


def hankel_prefix(n):
    # Each entry is the determinant of a consecutive shifted Hankel minor.
    current = apery_terms(2*n)
    previous = [1] * (len(current) + 2)
    result = [current[0]]
    for size in range(1, n + 1):
        new = []
        for j in range(len(current)-2):
            numerator = current[j]*current[j+2] - current[j+1]**2
            value, residue = divmod(numerator, previous[j+2])
            assert residue == 0 and value > 0
            new.append(value)
        previous, current = current, new
        result.append(current[0])
    return result


if __name__ == "__main__":
    cli = ArgumentParser()
    cli.add_argument("--maximum", type=int, default=48)
    args = cli.parse_args()
    if args.maximum < 3:
        cli.error("maximum must be at least 3")
    data = hankel_prefix(args.maximum)
    assert data[:4] == [1, 48, 161856, 39002646528]
    with localcontext() as ctx:
        ctx.prec = 36
        t = (1 + Decimal(2).sqrt())**4 / 4
        print("capacity", t)
        print(" n       D_n^(1/n^2)    (D_n/D_(n-1))^(1/2n)     (D_n/D_(n-1))/t^(2n-1)")
        for n in sorted({k for k in (4, 8, 16, 24, 32, 48, args.maximum) if k <= args.maximum}):
            log_d = Decimal(data[n]).ln()
            log_h = log_d - Decimal(data[n-1]).ln()
            x = (log_d / n**2).exp()
            y = (log_h / (2*n)).exp()
            z = (log_h - (2*n-1)*t.ln()).exp()
            print("{:2d} {:20.12f} {:22.12f} {:23.12f}".format(n, x, y, z))
