"""Check 2: Robin's inequality.

Robin (1984): the Riemann Hypothesis is TRUE if and only if
    sigma(n) < e^gamma * n * ln(ln(n))      for every n > 5040,
where sigma(n) is the sum of the divisors of n and gamma is Euler's constant (e^gamma ~ 1.78107).
So a single n > 5040 that breaks it would disprove RH.

Part A: every n up to N, computed directly with a divisor-sum sieve.
Part B: colossally abundant (CA) numbers, the numbers with the most divisors for their size,
        which come closest to breaking the inequality. Built one prime at a time (each CA number is
        the previous one times the prime that raises sigma(n)/n the most per unit of log n), and
        checked with exact integer arithmetic for their factorizations and high-precision logs.
"""
import sys, json, math, time
import numpy as np
import mpmath as mp

EG = math.exp(0.5772156649015329)


def part_a(N):
    s = np.zeros(N + 1, dtype=np.int64)
    for d in range(1, N + 1):
        s[d::d] += d
    n = np.arange(N + 1, dtype=np.float64)
    with np.errstate(divide='ignore', invalid='ignore'):
        ratio = s / (n * np.log(np.log(n)))
    small = [int(k) for k in range(3, 5041) if ratio[k] >= EG]
    big = ratio[5041:]
    i = int(np.argmax(big)) + 5041
    # running record holders above 5040 (the n that set a new high for the ratio)
    recs, best = [], 0
    for k in range(5041, N + 1):
        if ratio[k] > best:
            best = ratio[k]; recs.append([k, round(float(best), 6)])
    return {"N": N, "violations_above_5040": int(np.sum(big >= EG)), "max_ratio": float(ratio[i]), "max_ratio_at": i,
            "e_gamma": EG, "exceptions_up_to_5040": small, "record_holders": recs[-25:]}


def primes_upto(m):
    s = bytearray([1]) * (m + 1); s[0:2] = b'\x00\x00'
    for i in range(2, int(m ** .5) + 1):
        if s[i]: s[i * i::i] = bytearray(len(s[i * i::i]))
    return [i for i in range(m + 1) if s[i]]


def part_b(max_digits):
    mp.mp.dps = 60
    P = primes_upto(200000)
    exp = {}                     # exponent of each prime in the current CA number
    logn = mp.mpf(0)             # ln n
    logsig_over_n = mp.mpf(0)    # ln(sigma(n)/n)
    rows, worst = [], None
    gain = lambda p, a: mp.log((mp.mpf(p) ** (a + 2) - 1) / (mp.mpf(p) ** (a + 1) - 1)) - mp.log(p)  # change in ln(sigma/n) when a -> a+1
    # candidates: for each prime currently used, raising its exponent; plus the next unused prime
    import heapq
    heap, k, nxt = [], 0, 0
    def push(p, a):
        heapq.heappush(heap, (-(gain(p, a) / mp.log(p)), p))
    push(P[0], 0); nxt = 1
    while True:
        _, bp = heapq.heappop(heap)
        a = exp.get(bp, 0)
        logsig_over_n += gain(bp, a)
        logn += mp.log(bp)
        exp[bp] = a + 1
        push(bp, a + 1)
        if a == 0:                      # first use of this prime: the next prime becomes a candidate
            push(P[nxt], 0); nxt += 1
        k += 1
        digits = float(logn / mp.log(10))
        if digits > max_digits:
            break
        if logn > mp.log(5040):
            ratio = mp.e ** logsig_over_n / mp.log(logn)          # sigma(n) / (n ln ln n)
            margin = float(EG - ratio)
            row = [k, round(digits, 2), float(ratio), margin]
            if worst is None or margin < worst[3]:
                worst = row
            if margin <= 0:
                rows.append(row + ["VIOLATION"])
            elif k <= 40 or k % 200 == 0:
                rows.append(row)
    return {"ca_numbers_checked": k - 1, "largest_digits": round(digits, 1), "violations": sum(1 for r in rows if len(r) == 5),
            "closest": worst, "sample": rows[:40] + rows[40::max(1, len(rows[40:]) // 40)],
            "largest_prime_used": max(exp)}


if __name__ == "__main__":
    N = int(sys.argv[1]) if len(sys.argv) > 1 else 10_000_000
    D = int(sys.argv[2]) if len(sys.argv) > 2 else 10000
    t0 = time.time(); A = part_a(N); t1 = time.time(); B = part_b(D); t2 = time.time()
    out = {"A": A, "B": B, "seconds": [round(t1 - t0, 1), round(t2 - t1, 1)]}
    json.dump(out, open("check2_result.json", "w"), indent=1)
    print(json.dumps({k: v for k, v in A.items() if k != "record_holders"}, indent=1))
    print(json.dumps({k: v for k, v in B.items() if k != "sample"}, indent=1), out["seconds"])
