"""Compute the first point of contact using an exact integer slope comparison."""
from math import comb, log, pi, sqrt


def contact(k):
    if k < 1:
        raise ValueError("k must be positive")
    n = 2 * k
    denom = 1 << n
    coefficient = comb(n, k)
    partial = (denom + coefficient) // 2
    while n * coefficient > 2 * (denom - partial):
        partial = 2 * partial - coefficient
        coefficient = coefficient * (n + 1) // (n + 1 - k)
        denom *= 2
        n += 1
    return n


def direct(k):
    from fractions import Fraction
    slopes = [Fraction(sum(comb(n, j) for j in range(k + 1, n + 1)), n * 2**n)
              for n in range(1, 4 * k + 15)]
    return 1 + slopes.index(max(slopes))


if __name__ == "__main__":
    for k in range(1, 41):
        assert contact(k) == direct(k)
    print("k  exact m_k  continuous approximation  m_k - approximation")
    for k in (10, 40, 100, 1000, 10000, 100000):
        L = log(k / pi)
        t = 2 * k + sqrt(2 * k * L) + L / 2 + 0.5
        m = contact(k)
        print(f"{k:6} {m:8} {t:17.6f} {m-t:12.6f}")
