#!/usr/bin/env python3
"""
Independent replay of isitsolved.com dataset "least-nonresidue".

Dataset claims: for every odd prime p < 10^7, the least quadratic nonresidue
n_p mod p, together with the distribution of n_p and a "scatter" list of the
primes p < 10^7 with n_p >= 11 (the large cases).

We recompute from scratch with our own code (no reuse of the site's program):
  * a bytearray sieve of Eratosthenes to 10^7,
  * for each odd prime p, the least n >= 2 with n^((p-1)/2) = -1 (mod p)
    via Euler's criterion, computed with Python's built-in pow (exact modular
    exponentiation; no floating point anywhere),
  * the distribution table and the large-case list.

Then we compare every number with the published JSON and print a verdict.
"""
import json, sys, time

LIMIT = 10**7

def sieve(n):
    """Boolean sieve: is_prime[i] True iff i is prime, for i < n."""
    is_prime = bytearray([1]) * n
    is_prime[0:2] = b"\x00\x00"
    for i in range(2, int(n ** 0.5) + 1):
        if is_prime[i]:
            start = i * i
            is_prime[start:n:i] = bytearray(len(range(start, n, i)))
    return is_prime

def main():
    t0 = time.time()
    is_prime = sieve(LIMIT)
    odd_primes = [p for p in range(3, LIMIT) if is_prime[p]]
    print(f"sieve done in {time.time()-t0:.1f}s; odd primes < 10^7: {len(odd_primes)}")

    counts = {}
    large = []          # (p, n_p) with n_p >= 11
    for p in odd_primes:
        e = (p - 1) // 2
        n = 2
        while pow(n, e, p) != p - 1:
            n += 1
        counts[n] = counts.get(n, 0) + 1
        if n >= 11:
            large.append([p, n])
    print(f"scan done in {time.time()-t0:.1f}s total")

    d = json.load(open("least-nonresidue.json"))
    ok = True

    # --- 1. prime count
    print(f"\nprime count: ours {len(odd_primes)} vs published {d['primes']}")
    ok &= len(odd_primes) == d["primes"]

    # --- 2. distribution, every row
    print("\ndistribution (np, ours, published, ours-share, published-share)")
    pub = {row["np"]: row for row in d["distribution"]}
    total = len(odd_primes)
    for np_ in sorted(set(counts) | set(pub)):
        ours = counts.get(np_, 0)
        prow = pub.get(np_)
        pcount = prow["count"] if prow else None
        pshare = prow["share"] if prow else None
        ourshare = ours / total
        flag = ""
        if pcount != ours:
            flag = "  <-- COUNT MISMATCH"; ok = False
        if pshare is not None and abs(pshare - ourshare) > 5e-13:
            flag += "  <-- SHARE MISMATCH"; ok = False
        print(f"  {np_:3d}  {ours:7d}  {str(pcount):>7s}  {ourshare:.12f}  "
              f"{pshare if pshare is not None else float('nan'):.12f}{flag}")
    # shares should sum to 1
    print(f"  sum of our shares: {sum(counts.values())/total:.15f}")

    # --- 3. the large cases (scatter)
    print(f"\nlarge cases: ours {len(large)} vs published {len(d['scatter'])}")
    ok &= len(large) == len(d["scatter"])
    pub_large = [list(map(int, r)) for r in d["scatter"]]
    if large != pub_large:
        ok = False
        # find first difference
        for i, (a, b) in enumerate(zip(large, pub_large)):
            if a != b:
                print(f"  first difference at index {i}: ours {a}, published {b}")
                break
        if len(large) != len(pub_large):
            print(f"  length differs: ours {len(large)}, published {len(pub_large)}")
            print(f"  ours tail: {large[-5:]}")
            print(f"  published tail: {pub_large[-5:]}")
    else:
        print("  every (p, n_p) pair matches, in the same order")

    # --- 4. the quoted record n_p / ln p
    import math
    best = max(large, key=lambda r: r[1] / math.log(r[0]))
    print(f"\nlargest n_p/ln p among p < 10^7: {best[1]/math.log(best[0]):.6f} at p = {best[0]} (n_p = {best[1]})")

    print("\nVERDICT:", "MATCH" if ok else "MISMATCH")
    return 0 if ok else 1

if __name__ == "__main__":
    sys.exit(main())
