"""Independent check of iis:2611.00056 (Lewis-Won, arXiv:2609.03081v1, Conjecture 3.17).

(3.1): F_n(m) = sum_{k=1}^m (S(m,k) k^(n-2m) k!)^2 on the feasible range 0 <= 2m <= n.
m_* : the unique positive root of n = ln(x+1)/ln(1+1/x) + 2x  (Prop. 3.16).
Conjecture 3.17: the maximum of F_n is attained at some m in (m_*, m_*+2).
Exact integers for F_n; m_* by bisection in 60-digit decimal arithmetic.
"""
import sys
from decimal import Decimal, getcontext
from fractions import Fraction
import math
from math import factorial

getcontext().prec = 60
N = int(sys.argv[1])

S = [[0] * (N + 2) for _ in range(N + 2)]
S[0][0] = 1
for a in range(1, N + 1):
    for b in range(1, a + 1):
        S[a][b] = S[a - 1][b - 1] + b * S[a - 1][b]

def F(n, m):
    return sum((S[m][k] * k ** (n - 2 * m) * factorial(k)) ** 2 for k in range(1, m + 1))

def f(x):
    return (x + 1).ln() / (1 + 1 / x).ln() + 2 * x

def m_lower(n):
    """Bracket [lo, hi] around the root; f is strictly increasing on x > 0."""
    lo, hi = Decimal("1e-30"), Decimal(n)
    for _ in range(220):
        mid = (lo + hi) / 2
        lo, hi = (mid, hi) if f(mid) < n else (lo, mid)
    return lo, hi

# n = 3: the root is exactly 1, since f(1) = ln2/ln2 + 2 = 3.
EXACT_ROOT = {3: 1}
assert abs(f(Decimal(1)) - 3) < Decimal("1e-50")
assert [F(3, m) for m in (0, 1)] == [0, 1]
# Outside the feasible range the formula has no meaning, but plugged in at n=3, m=2 it gives 2
# (S(2,1)*1^-1*1! = 1 and S(2,2)*2^-1*2! = 1), so the refutation rests on 2m <= n.
assert sum((S[2][k] * Fraction(k) ** (3 - 4) * factorial(k)) ** 2 for k in (1, 2)) == 2

def in_open_interval(n, m, lo, hi):
    if n in EXACT_ROOT:
        x = EXACT_ROOT[n]
        assert lo <= x <= hi
        return x < m < x + 2
    if hi < m < lo + 2:
        return True
    if m <= lo or m >= hi + 2:
        return False
    raise ValueError(f"n={n}: m={m} is within the root bracket of an endpoint; decide exactly")

# The paper's exhaustive r(n) for n = 4..8 (Section 3.4) is attained by shape (m,1,...,1,m).
assert [max(F(n, m) for m in range(n // 2 + 1)) for n in range(4, 9)] == [5, 17, 73, 469, 3493]

fails, min_gap, where = [], None, {}
for n in range(1, N + 1):
    vals = {m: F(n, m) for m in range(n // 2 + 1)}
    best = max(vals.values())
    argmax = [m for m, v in vals.items() if v == best]
    lo, hi = m_lower(n)
    ok = any(in_open_interval(n, m, lo, hi) for m in argmax)
    if not ok:
        fails.append(n)
    if n >= 4:
        gap = min(min(abs(m - lo), abs(m - lo - 2)) for m in argmax)
        min_gap = gap if min_gap is None else min(min_gap, gap)
        c = math.ceil(lo)
        assert c == math.ceil(hi)
        key = tuple(m - c for m in argmax)
        where[key] = where.get(key, 0) + 1
    if n <= 12 or not ok:
        print(f"n={n:3d} m_*={float(lo):.6f} argmax={argmax} F_max={best} in_interval={ok}")
print("checked n = 1 ..", N, "| failures:", fails)
print("n>=4: smallest distance from a maximizer to an endpoint:", float(min_gap))
print("n>=4: maximizer minus ceil(m_*) -> count of n:", where)
