#!/usr/bin/env python3
"""Independent cross-check of the continued fraction (separate input, separate algorithm).

Reads the first `ndig` decimal digits from data/e_plus_pi_<D>.txt (digits confirmed by both MPFR
and mpmath), forms the interval [d/10^n, (d+1)/10^n] that must contain e + pi, and runs plain
simultaneous Euclid on both endpoints (no divide-and-conquer, no binary input). The resulting
common prefix must agree with the prefix of data/cf_terms_<D>.txt.

Usage: python verify_cf.py D ndig
"""
import sys, os
from gmpy2 import mpz
HERE = os.path.dirname(os.path.abspath(__file__)); DATA = os.path.join(HERE, "..", "data")
D = int(sys.argv[1]); ndig = int(sys.argv[2])
s = open(os.path.join(DATA, f"e_plus_pi_{D}.txt")).read().strip().replace(".", "")
assert len(s) >= ndig + 1
d = mpz(s[: ndig + 1]); den = mpz(10) ** ndig
a, b, c, e = d, den, d + 1, den          # L = a/b, U = c/e
terms = []
while True:
    qa, qc = a // b, c // e
    if qa != qc: break
    ra, rc = a - qa * b, c - qc * e
    if ra == 0 or rc == 0: break
    terms.append(int(qa))
    a, b, c, e = e, rc, b, ra
ref = [int(x) for x in open(os.path.join(DATA, f"cf_terms_{D}.txt")).read().split()]
n = len(terms)
agree = ref[:n] == terms
print(f"naive Euclid from {ndig} decimal digits: {n} certified terms; agree with fast-algorithm prefix: {agree}")
if not agree:
    i = next(i for i in range(n) if ref[i] != terms[i]); print("first mismatch at index", i); sys.exit(1)
