"""Erdős #341 (Li 2026): brute-force greedy extension of the seed vs the closed form S
used in LiAlreadyExists/Erdos-341 c1d9121 (LeanProject/Erdos341.lean).

Greedy rule (erdosproblems.com/341): after the seed, the next term is the least integer
above the last one that is not a_i + a_j (i, j <= n, equal indices allowed).
For positive terms this is: n > 97 is selected iff n is not a sum of two selected numbers.

Usage: python -X utf8 e341_check.py [N]   (default N = 2_000_000)
"""
import sys
import numpy as np

N = int(sys.argv[1]) if len(sys.argv) > 1 else 2_000_000
SEED = [1, 2, 3, 5, 7, 13, 22, 27, 28, 32, 36, 40, 47, 48, 52, 63, 71, 77, 81, 89, 97]

# --- brute force greedy extension ---------------------------------------------------
sel = np.zeros(N + 1, dtype=bool)
sums = np.zeros(2 * N + 2, dtype=bool)
elems = np.zeros(N + 1, dtype=np.int64)
cnt = 0


def add(x):
    global cnt
    elems[cnt] = x
    cnt += 1
    sel[x] = True
    sums[x + elems[:cnt]] = True  # x + y for every selected y <= x (incl. y = x)


for x in SEED:
    add(x)
for n in range(98, N + 1):
    if not sums[n]:
        add(n)

# --- closed form from the Lean file -------------------------------------------------
def Y0(n):
    if n == 0:
        return True
    k = 1
    while 4 * k <= n:
        if n < 8 * k:
            return True
        k *= 8
    return False


def Y1(n):
    if 1 <= n <= 3:
        return True
    k = 1
    while 16 * k <= n + 1:
        if n < 32 * k:
            return True
        k *= 8
    return False


def Y2(n):
    if n <= 1 or 7 <= n <= 15:
        return True
    k = 1
    while 64 * k <= n + 1:
        if n < 128 * k:
            return True
        k *= 8
    return False


D = {1, 2, 5, 13, 27, 36, 47}
B = {3, 22, 32, 40, 48}


def S(n):
    r, q = n % 49, n // 49
    return (n in D or r in B or (r == 7 and Y0(q)) or (r == 14 and Y1(q))
            or (r == 28 and Y2(q)))


closed = np.array([S(n) for n in range(N + 1)])
mism = np.nonzero(closed != sel)[0]
print(f"N = {N}: greedy terms = {cnt}, closed-form terms = {int(closed.sum())}, mismatches = {len(mism)}")
assert len(mism) == 0, mism[:10]
assert [n for n in range(98) if sel[n]] == SEED

# --- controller gate identities (Lean: controller_01/12/20), checked on [0, M] -----
M = N // 49 + 1
y = [np.array([f(n) for n in range(M + 1)]) for f in (Y0, Y1, Y2)]


def pairsum(a):
    idx = np.nonzero(a)[0]
    out = np.zeros(2 * len(a), dtype=bool)
    for i in idx:
        out[i + idx] = True
    return out[: len(a)]


ps = [pairsum(a) for a in y]
assert np.array_equal(y[1], ~ps[0]), "gate01"
assert np.array_equal(y[2], ~ps[1]), "gate12"
assert np.array_equal(y[0][1:], ~ps[2][:-1]), "gate20"
print(f"gate identities Y1 = not PairSum Y0, Y2 = not PairSum Y1, Y0(n+1) = not PairSum Y2(n): OK for n <= {M}")

# --- the gaps: rail 7 mod 49 carries Y0, whose blocks [4*8^k, 8*8^k) grow -----------
terms = np.nonzero(sel)[0]
gaps = np.diff(terms)
print("first 40 terms:", terms[:40].tolist())
print("max gap up to N:", int(gaps.max()), " distinct gaps:", sorted(set(gaps.tolist()))[:30])
r7 = [int(q) for q in range(M) if sel[49 * q + 7]] if 49 * (M - 1) + 7 <= N else None
print("q with 49q+7 selected (first 30):", r7[:30] if r7 else None)
