"""2kwas: independent check of iis:2611.00272 (prime-period bound for progressions of integral Fibonacci means).

A = { n >= 2 : n | F_1 + ... + F_n }.  Our own code, written from the definitions; the authors' Lean project is not run.

usage: python3 -I fib_ap_check.py > fib_ap_check.out
"""
from math import gcd, isqrt
import numpy as np

N = 3_000_000          # membership of A is computed for 2 <= n <= N
D = 3000               # differences checked


def fib_pair(m):
    """(F_m, F_{m+1}) exactly"""
    a, b = 0, 1
    for bit in bin(m)[2:]:
        a, b = a * (2 * b - a), a * a + b * b
        if bit == "1":
            a, b = b, a + b
    return a, b


def primes_upto(x):
    s = bytearray([1]) * (x + 1); s[0:2] = b"\x00\x00"
    for i in range(2, isqrt(x) + 1):
        if s[i]: s[i * i::i] = bytearray(len(s[i * i::i]))
    return [i for i in range(x + 1) if s[i]]


def pisano(p):
    a, b, k = 0, 1, 0
    while True:
        a, b, k = b, (a + b) % p, k + 1
        if (a, b) == (0, 1): return k


# ------------------------------------------------------------------ 1. the identity and membership of A
F = [0, 1]
for _ in range(200): F.append(F[-1] + F[-2])
print("1 + F_1 + ... + F_n = F_(n+2) for n <= 150:", all(1 + sum(F[1:n + 1]) == F[n + 2] for n in range(151)))

# F_(n+2) mod n for all n at once: fast doubling over the bits of n+2, vectorised (int64 is enough since n^2 < 2^63)
n = np.arange(N + 1, dtype=np.int64); n[0] = 1; n[1] = 1
m = n + 2
a = np.zeros(N + 1, dtype=np.int64); b = np.ones(N + 1, dtype=np.int64) % n
for bit in range(int(m.max()).bit_length() - 1, -1, -1):
    a, b = (a * ((2 * b - a) % n)) % n, (a * a + b * b) % n
    sel = ((m >> bit) & 1).astype(bool)
    a2 = np.where(sel, b, a); b2 = np.where(sel, (a + b) % n, b)
    a, b = a2, b2
inA = np.zeros(N + 1, dtype=bool)
inA[2:] = ((a[2:] - 1) % n[2:]) == 0
A = np.flatnonzero(inA)
print("elements of A up to %d: %d; the first 20: %s" % (N, len(A), A[:20].tolist()))
# independent cross-checks: direct sums modulo n, and exact big-integer Fibonacci numbers
ok_direct = True
for k in range(2, 3001):
    s, x, y = 0, 0, 1
    for _ in range(k):
        x, y = y, (x + y) % k
        s = (s + x) % k
    ok_direct &= ((s == 0) == bool(inA[k]))
print("membership by direct summation of F_1..F_n mod n agrees for 2 <= n <= 3000:", ok_direct)
rng = np.random.default_rng(272)
sample = rng.integers(2, N, size=300).tolist() + A[rng.integers(0, len(A), size=300)].tolist()
print("membership by exact F_(n+2) agrees on 600 sampled n (300 random, 300 from A):",
      all(((fib_pair(int(k) + 2)[0] - 1) % int(k) == 0) == bool(inA[int(k)]) for k in sample))

# ------------------------------------------------------------------ 2. the key lemma, by brute force over residues
P = [p for p in primes_upto(60)]
ok_lemma = True; cases = 0
for p in P:
    T = pisano(p)
    Fm = [0, 1]
    for _ in range(3 * T + 5): Fm.append((Fm[-1] + Fm[-2]) % p)
    for bb in range(T):
        for d in range(1, T + 1):
            h = (p * d) % T
            if Fm[bb] == 1 and Fm[(bb + h) % T] == 1 and Fm[(bb + 2 * h) % T] == 1:
                cases += 1
                good = (d % T == 0)
                if p != 5: ok_lemma &= good
                elif not good and p == 5 and d == 4 and bb == 1:
                    print("p = 5 is a genuine exception: F_1 = F_21 = F_41 = 1 mod 5 with d = 4, while pi(5) = 20 does not divide 4")
print("lemma: for primes p <= 60, p != 5, every b, d with F_b = F_(b+pd) = F_(b+2pd) = 1 (mod p) has pi(p) | d:",
      ok_lemma, "(%d triples tested)" % cases)

# ------------------------------------------------------------------ 3. maximal progressions in A with difference d <= D
inA_list = inA  # alias
primes = primes_upto(10000)
fd = {d: fib_pair(d) for d in range(1, D + 1)}
checks = 0; viol = 0; viol_cons = 0; worst = []
maxlen = {}
for d in range(1, D + 1):
    Fd, Fd1 = fd[d]
    g = gcd(Fd, Fd1 - 1)
    p_star = next(p for p in primes if p != 5 and d % p and g % p)
    bound = 3 * p_star - 1
    best = 0
    starts = A[~inA[np.maximum(A - d, 0)] | (A - d < 2)]
    for a0 in starts.tolist():
        k = 1
        while a0 + k * d <= N and inA[a0 + k * d]: k += 1
        best = max(best, k)
        if k >= 6:
            for p in primes:
                if 3 * p > k: break
                if p == 5: continue
                checks += 1
                if not (d % p == 0 or (Fd % p == 0 and Fd1 % p == 1)): viol += 1
            prod = 1
            for p in primes:
                if 3 * p > k: break
                prod *= p
            if (5 * d * g) % prod: viol_cons += 1
    maxlen[d] = (best, bound)
    worst.append((best / bound, d, best, bound, p_star))
print("progressions with difference d <= %d inside [2, %d]:" % (D, N))
print("  (prime, progression) checks of the theorem (progressions of length >= 6): %d, violations: %d" % (checks, viol))
print("  'product of the primes up to k/3 divides 5 d gcd(F_d, F_(d+1)-1)': violations %d" % viol_cons)
print("  longest progression never exceeds 3p-1 (p = first prime != 5 dividing neither d nor the gcd):",
      all(b <= c for b, c in maxlen.values()))
top = sorted(maxlen.items(), key=lambda kv: -kv[1][0])[:8]
print("  longest progressions found: " + ", ".join("d=%d: %d terms (bound %d)" % (d, b, c) for d, (b, c) in top))
worst.sort(reverse=True)
print("  closest to the bound: " + ", ".join("d=%d: %d of %d (p=%d)" % (d, b, c, p) for r, d, b, c, p in worst[:6]))

# ------------------------------------------------------------------ 4. the example d = 24
F24, F25 = fib_pair(24)
g24 = gcd(F24, F25 - 1)
print("d = 24: (F_24, F_25) = (%d, %d) = (%d, %d) mod 7; gcd(F_24, F_25 - 1) = %d; first prime != 5 dividing neither 24 nor %d: %d; "
      "bound 3*7-1 = 20; longest progression of difference 24 found up to %d: %d terms"
      % (F24, F25, F24 % 7, F25 % 7, g24, g24, next(p for p in primes if p != 5 and 24 % p and g24 % p), N, maxlen[24][0]))
run = []
for a0 in A.tolist():
    k = 1
    while a0 + k * 24 <= N and inA[a0 + k * 24]: k += 1
    if k == maxlen[24][0]: run.append(a0)
print("  starts of the longest difference-24 progressions:", run[:10])
