#!/usr/bin/env python3
# =====================================================================
#  Verificación de «Una restricción de exponentes para los ciclos del
#  mapa de retorno» (sección 7.4 de collatz.es).
#
#  Lenguaje: Python 3 (probado con 3.11) + mpmath 1.3.0.
#  Aritmética: enteros exactos; mpmath con precisión configurable en
#  las comparaciones con logaritmos. El bloque (3) se ejecuta a 60 y a
#  250 dígitos decimales y ambos resultados deben coincidir.
#
#  Definición literal de R, sobre los enteros impares positivos:
#      si Q = 1 (mod 4):  r = v2(3Q+1) ;  R(Q) = 3^(r-2) (3Q+1) / 2^r
#      si Q = 3 (mod 4):  r = v2(Q+1)  ;  R(Q) = 3^(r-2) (Q+1)  / 2^r
#
#  Bloques:
#
#   (1) IDENTIDAD DE EXPONENTES  (Teorema 2.1)
#         2E = 2S - 5d + 5m + 5 b_exp + a_con + 6 b2 + 4 b3 + 2 b4
#       Comprobada por fuerza bruta sobre multiplicidades aleatorias.
#
#   (2) RACHAS DE B_5  (Teorema 3.2)
#       Con 5Q - 27 = 2*32^L*t,  t = 3*2^{-(L+1)} (mod 5)  y
#       t != 0 (mod 32), la órbita de R aplica B_5 exactamente L veces
#       consecutivas. Se comprueba construyendo Q y recorriendo R.
#       Se comprueba además que t = 0 (mod 32) es la unica forma de
#       prolongar la racha.
#
#   (3) TABLA DE COTAS SUPERIORES  (Proposición 4.1)
#       Para cada m se criba (d,S) con  0 < Lambda < cota, donde
#           Lambda = d log3 - S log(3/2),
#           cota   = 3d / (2 (2^{eta_m * Emin} - 1)),
#           eta_m  = c / ((1+c)^m - 1),   c = log_2(3/2),
#           Emin   = max( S - floor(5(d-m)/2),            [nueva]
#                         floor(gamma (d-2m)) + 1 ).      [de la 7.3]
#       Parada en S: cuando Lambda supera la cota que daria la segunda
#       componente por si sola (la mayor posible).
#       Parada en d: 4000 unidades tras el ultimo superviviente.
#       Control: m=1 debe dar d_max = 27.
#
#   (4) CIERRE  (Teorema 5.1)
#       Con la cota inferior d > 27766 de la seccion 7.3, queda
#       excluido todo m cuyo d_max(m) no la supere.
#
#  Uso:  python3 verificacion_exponentes.py [1|2|3|4|todo] [m_max]
# =====================================================================

import sys, random
from mpmath import mp, mpf, log, floor, power

M_MAX_DEFECTO = 13
D_INFERIOR = 27766          # cota inferior de la seccion 7.3

# ---------------------------------------------------------------------
def v2(x):
    c = 0
    while x % 2 == 0:
        x //= 2; c += 1
    return c

def R(Q):
    if Q % 4 == 1:
        r = v2(3*Q + 1)
        return 3**(r-2) * (3*Q + 1) // 2**r
    r = v2(Q + 1)
    return 3**(r-2) * (Q + 1) // 2**r

def rama(Q):
    """Devuelve (tipo, r) de la rama que R aplica en Q."""
    if Q % 4 == 1: return ('A', v2(3*Q + 1))
    return ('B', v2(Q + 1))

def constantes(dps):
    mp.dps = dps
    L2, L3 = log(2), log(3)
    L32 = L3 - L2
    alpha = L3 / L32
    gamma = log(mpf(31)/27) / (2*L32)
    c = L32 / L2
    return L2, L3, L32, alpha, gamma, c

# ---------------------------------------------------------------------
#  (1) La identidad de exponentes
# ---------------------------------------------------------------------
def identidad(muestras=20000, semilla=7, verbose=True):
    random.seed(semilla)
    fallos = 0
    for _ in range(muestras):
        m = random.randint(1, 8)
        a_exp = random.randint(0, m); b_exp = m - a_exp
        aC = random.randint(0, 9)
        b2 = random.randint(0, 9); b3 = random.randint(0, 9)
        b4 = random.randint(0, 9); b5 = random.randint(0, 9)
        E = (sum(random.randint(3, 30) for _ in range(a_exp)) +
             sum(random.randint(6, 30) for _ in range(b_exp)))
        N = aC + b2 + b3 + b4 + b5
        k = m + N
        b = b_exp + b2 + b3 + b4 + b5
        d = k + b
        S = E + 2*aC + 2*b2 + 3*b3 + 4*b4 + 5*b5
        if 2*E != 2*S - 5*d + 5*m + 5*b_exp + aC + 6*b2 + 4*b3 + 2*b4:
            fallos += 1
    if verbose:
        print(f"   {muestras} casos aleatorios: "
              f"{'identidad verificada' if fallos == 0 else str(fallos)+' FALLOS'}")
    if fallos:
        raise RuntimeError("la identidad de exponentes no se verifica")
    return True

# ---------------------------------------------------------------------
#  (2) Rachas de B_5
# ---------------------------------------------------------------------
def racha_B5(Q):
    """Numero de ramas B_5 consecutivas que R aplica desde Q."""
    n = 0
    while True:
        f, r = rama(Q)
        if f == 'B' and r == 5:
            n += 1; Q = R(Q)
        else:
            return n

def rachas(Lmax=8, verbose=True):
    ok = True
    for L in range(1, Lmax+1):
        # t = 3 * 2^{-(L+1)} (mod 5)   y   t != 0 (mod 32)
        t = None
        for cand in range(1, 10000):
            if (2 * 32**L * cand + 27) % 5: continue
            if cand % 32 == 0: continue
            t = cand; break
        Q = (2 * 32**L * t + 27) // 5
        n = racha_B5(Q)
        bien = (n == L)
        ok &= bien
        # y con t multiplo de 32 la racha se prolonga
        t2 = None
        for cand in range(32, 200000, 32):
            if (2 * 32**L * cand + 27) % 5: continue
            t2 = cand; break
        Q2 = (2 * 32**L * t2 + 27) // 5
        n2 = racha_B5(Q2)
        if verbose:
            print(f"   L={L}: t={t:5d} -> Q={Q:>22}  racha {n:2d}"
                  f"   {'OK' if bien else 'FALLA'}"
                  f"    | t={t2} (mult. de 32) -> racha {n2}"
                  f" {'(se prolonga)' if n2 > L else '(NO se prolonga)'}")
        ok &= (n2 > L)
    if not ok:
        raise RuntimeError("la construccion de rachas no se verifica")
    return True

# ---------------------------------------------------------------------
#  (3) Tabla de cotas superiores
# ---------------------------------------------------------------------
def tabla(m_max=M_MAX_DEFECTO, dps=60, verbose=True):
    L2, L3, L32, alpha, gamma, c = constantes(dps)
    out = {}; limites = {}
    if verbose:
        print("     m    eta_m      d_max    limite de recorrido")
    for m in range(1, m_max+1):
        et = c / ((1+c)**m - 1)

        def cota(d, E):
            z = power(2, et*E)
            return 3*mpf(d)/(2*(z-1)) if z > 1 else mpf('inf')

        dm = 0; vacio = 0; d = 3
        while d < 300000:
            e2 = int(floor(gamma*(d - 2*m))) + 1
            if e2 < 1: e2 = 1
            tope = cota(d, e2)              # mayor cota posible para este d
            S = int(floor(alpha*d))
            if d*L3 - S*L32 <= 0: S -= 1
            hay = False
            while S >= 1:
                Lam = d*L3 - S*L32
                if Lam >= tope: break       # ningun S menor puede sobrevivir
                E = max(S - (5*(d-m))//2, e2)
                if Lam < cota(d, E):
                    hay = True; break
                S -= 1
            if hay: dm = d; vacio = 0
            else: vacio += 1
            d += 1
            if vacio > 4000 and dm > 0: break
        out[m] = dm; limites[m] = d
        if verbose:
            print(f"    {m:2d}  {mp.nstr(et,7):>9}  {dm:>9}  {d:>12}")
    return out, limites

# ---------------------------------------------------------------------
def main():
    que = sys.argv[1] if len(sys.argv) > 1 else 'todo'
    m_max = int(sys.argv[2]) if len(sys.argv) > 2 else M_MAX_DEFECTO

    if que in ('1', 'todo'):
        print("(1) IDENTIDAD DE EXPONENTES")
        identidad()
        print()

    if que in ('2', 'todo'):
        print("(2) RACHAS DE B_5")
        rachas()
        print()

    res = None
    if que in ('3', '4', 'todo'):
        print("(3) TABLA DE COTAS SUPERIORES")
        res, lim = tabla(m_max, 60)
        r2, _ = tabla(m_max, 250, verbose=False)
        print(f"   repetido a 250 digitos: "
              f"{'identico' if res == r2 else 'DIFIERE'}")
        if res.get(1) == 27:
            print("   control: m=1 da d_max = 27")
        print()

    if que in ('4', 'todo') and res:
        print("(4) CIERRE")
        ok = [m for m in res if res[m] <= D_INFERIOR]
        print(f"   cota inferior de la seccion 7.3: d > {D_INFERIOR}")
        print(f"   => no existen ciclos con m <= {max(ok) if ok else 0} "
              f"ramas expansivas")
        for m in sorted(res):
            marca = "excluido" if res[m] <= D_INFERIOR else "abierto"
            print(f"      m={m:2d}:  d_max = {res[m]:>6}   {marca}")

if __name__ == '__main__':
    main()
