"""Exact g(a,b) with a proved scan limit (Jaffe, arXiv 2610.17267, Sec. 3 definition).

g(a,b) = largest N not of the form a*x + b*y with x, y >= 0 and gcd(x, y) = 1.

Scan limit (proof in the report): write the solutions of a*x+b*y = N as
x_t = x0 + b*t, y_t = y0 - a*t, t = 0..R-1, with 0 <= x0 < b, so R > N/(ab) - 1.
If N is not expressible, every interior solution (x_t, y_t > 0) has a prime p | gcd(x_t, y_t);
p | N, and p blocks one residue class of t mod p.  At most two solutions are endpoints
(x_t = 0 or y_t = 0).  So a run of r >= R - 2 consecutive t is covered by one class per
prime of N, and inclusion-exclusion gives r < (2^w - 1) * prod_{i<=w} p_i/(p_i - 1), w = omega(N).
Hence N < ab*(B_w + 3) with p_1*...*p_w <= N.  L(a,b) = max of these over admissible w.
"""
from math import gcd, prod
from fractions import Fraction
from jaffe_g import g_val

PR = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]

def limit(a, b):
    ab = a * b; L = 3 * ab  # w = 0
    for w in range(1, len(PR)):
        E = prod(Fraction(p, p - 1) for p in PR[:w])
        bound = ab * ((2**w - 1) * E + 3)         # N < bound
        if prod(PR[:w]) < bound:                  # omega(N) = w possible for N < bound
            L = max(L, int(bound) + 1)
    assert prod(PR[:len(PR)-1]) > L, "extend PR"  # w >= 19 impossible below L (bound grows slower)
    return L

def g_exact(a, b):
    assert gcd(a, b) == 1 and a >= 1 and b >= 1
    if b == 1:
        a, b = b, a
    ainv = pow(a, -1, b) if b > 1 else 0
    return g_val(a, b, ainv, limit(a, b))

def reps(N, a, b):
    return [(x, (N - a*x)//b) for x in range(0, N//a + 1) if (N - a*x) % b == 0]

def check_inexpressible(N, a, b):
    """direct check, no shortcuts: every solution has gcd != 1"""
    R = reps(N, a, b)
    return all(gcd(x, y) != 1 for x, y in R), R

if __name__ == "__main__":
    assert g_exact(5, 7) == 156            # paper, Sec. 3
    for a, b in [(770, 3), (770, 9)]:
        print(a, b, "limit", limit(a, b), "g =", g_exact(a, b))
