#!/usr/bin/env python3
"""Independent verification of three counterexamples to Zhi-Wei Sun's conjectures in OEIS A234360.

  (i)   n = 4722: (k+1)^phi(n-k) + k           is composite for every 0 < k < n
  (ii)  n = 7588: k*(k+1)^phi(n-k) + 1         is composite for every 0 < k < n
  (ii') n = 3998: k*(k+1)^(phi(n-k)/2) - 1     is composite (or not an integer) for every 0 < k < n

Every k gets a PROOF of compositeness: either an explicit prime q < 10^6 with N = 0 (mod q), found
by modular exponentiation without building N and then re-checked on the full integer N, or a
Fermat witness 2^(N-1) != 1 (mod N).  phi is computed by trial division here (no libraries).
Usage: verify.py {c1|c3|c4}   (prints a summary line; exits 1 if any k is not certified)
"""
import sys
from multiprocessing import Pool
try:
    from gmpy2 import mpz, powmod
except ImportError:           # pure-Python fallback (slow but library-free)
    mpz = int; powmod = pow
def phi(m):
    r, x, p = m, m, 2
    while p * p <= x:
        if x % p == 0:
            while x % p == 0: x //= p
            r -= r // p
        p += 1
    if x > 1: r -= r // x
    return r
LIM = 10**6
sieve = bytearray([1]) * LIM; sieve[0] = sieve[1] = 0
for i in range(2, 1000):
    if sieve[i]: sieve[i*i::i] = bytearray(len(sieve[i*i::i]))
PR = [i for i in range(2, LIM) if sieve[i]]
CASES = {'c1': 4722, 'c3': 7588, 'c4': 3998}
def work(args):
    case, n, k = args
    e = phi(n - k)
    if case == 'c4':
        if e % 2:                       # phi odd only for n-k in {1,2}: need k+1 a perfect square
            r = int((k + 1) ** 0.5)
            while r * r > k + 1: r -= 1
            while (r + 1) ** 2 <= k + 1: r += 1
            if r * r != k + 1: return (k, 'not-a-square')
            base, ee = r, e
        else: base, ee = k + 1, e // 2
        f = lambda q: (k * pow(base, ee, q) - 1) % q
        N = None; build = lambda: k * mpz(base) ** ee - 1
    elif case == 'c1':
        f = lambda q: (pow(k + 1, e, q) + k) % q; build = lambda: mpz(k + 1) ** e + k
    else:
        f = lambda q: (k * pow(k + 1, e, q) + 1) % q; build = lambda: k * mpz(k + 1) ** e + 1
    for q in PR:
        if f(q) == 0:
            N = build()
            if N > q and N % q == 0: return (k, 'factor')
            break                        # N == q would be prime: fall through to the full test
    N = build()
    if N < 4: return (k, 'PRIME?' if N in (2, 3) else 'small-nonprime')
    return (k, 'fermat2' if powmod(2, N - 1, N) != 1 else 'PRIME?')
if __name__ == '__main__':
    case = sys.argv[1]; n = CASES[case]
    with Pool(6) as p: res = p.map(work, [(case, n, k) for k in range(1, n)], chunksize=8)
    tally = {}
    for k, t in res: tally[t] = tally.get(t, 0) + 1
    bad = [k for k, t in res if t == 'PRIME?']
    print(f"{case} n={n}: {n-1} values of k -> {tally}" + (f"  UNCERTIFIED k={bad[:5]}" if bad else "  ALL COMPOSITE: counterexample confirmed"), flush=True)
    sys.exit(1 if bad else 0)
