"""g(a,b) = largest N not of the form a*x+b*y with x,y>=0, gcd(x,y)=1 (Jaffe, arXiv 2610.17267).
Scan N downward from a limit L(a,b) = ab*(J+1)+a+b, where J bounds the run length of
consecutive t that one residue class per prime of N can cover (see is_rep note)."""
import sys
from math import gcd
import numpy as np
from numba import njit

@njit(cache=True)
def g_(a, b):
    while b:
        a, b = b, a % b
    return a

@njit(cache=True)
def is_rep(N, a, b, ainv):
    x = (N % b) * ainv % b          # smallest x>=0 with a*x = N mod b
    while a * x <= N:
        y = (N - a * x) // b
        if g_(x, y) == 1:
            return True
        x += b
    return False

@njit(cache=True)
def g_val(a, b, ainv, L):
    N = L
    while N >= 0:
        if not is_rep(N, a, b, ainv):
            return N
        N -= 1
    return -1

def g(a, b, mult=60):
    ainv = pow(a, -1, b) if b > 1 else 0
    return g_val(a, b, ainv, mult * a * b)

if __name__ == "__main__":
    print("g(5,7) =", g(5, 7), "(paper: 156)")
