"""Compute the first new-character norm at p = 37, n = 32 in exact arithmetic.

The p-1 primitive characters of order p modulo f = p² are the conjugates of
χ(g) = ζ_p for any generator g of (Z/fZ)×. Their primitive-value product is
the field norm of -B_{n,χ}/n. Write that element in the power basis of
π = ζ_p - 1. Since Φ_p(1+X) is Eisenstein, v_π(p)=p-1. The nonzero terms of
this power basis have distinct valuations mod p-1. Thus their minimum is the
valuation of the element, and equals the p-adic valuation of its field norm
(the residue degree is one).
"""
from fractions import Fraction
from math import comb, gcd
import sys


def bernoulli_numbers(n):
    result = [Fraction(1)]
    for k in range(1, n + 1):
        result.append(-sum(comb(k + 1, j) * result[j] for j in range(k)) / (k + 1))
    return result


def valuation(value, p):
    def exponent(integer):
        count = 0
        while integer % p == 0:
            integer //= p
            count += 1
        return count

    assert value != 0
    return exponent(value.numerator) - exponent(value.denominator)


p, n, g = 37, 32, 2
f = p**2
phi = p * (p - 1)
# Enumerating the full orbit verifies the chosen generator and assigns logs.
powers = [pow(g, j, f) for j in range(phi)]
assert len(set(powers)) == phi
assert set(powers) == {a for a in range(1, f) if gcd(a, f) == 1}
bernoulli = bernoulli_numbers(n)
coefficients = [Fraction(0)] * p
# f^(n-1)*B_n(a/f) = Σ_k binom(n,k)*B_k*a^(n-k)*f^k / f.
weights = [comb(n, k) * bernoulli[k] * f**k / (-n * f) for k in range(n + 1)]
for j, a in enumerate(powers):
    coefficients[j % p] += sum(weights[k] * a**(n-k) for k in range(n + 1))

# Eliminate ζ^(p-1) using Φ_p(ζ)=0, then put ζ=1+π.
zeta = [b - coefficients[-1] for b in coefficients[:-1]]
pi = [sum(comb(k, j) * zeta[k] for k in range(j, p-1)) for j in range(p-1)]
term_values = [(p-1)*valuation(b, p) + j for j, b in enumerate(pi) if b]
print("p =", p, " n =", n, " conductor =", f, " generator =", g)
print("B_n / n =", bernoulli[n] / n)
print("v_p(B_n/n) =", valuation(bernoulli[n] / n, p))
assert all(b.denominator == 1 for b in pi)
print("All coefficients in the π-basis are integers.")
print("Constant and linear coefficients mod 37 =", [int(b) % p for b in pi[:2]])
print("v_p(first new-character product) =", min(term_values))
assert min(term_values) > 0
print("v_p(first new-character product minus 1) = 0, by the ultrametric inequality")

# Optional independent norm computation in SymPy. The default check above uses
# only the standard library. Φ_p is monic, so the resultant multiplies all
# conjugates of the primitive character value exactly.
if "--resultant" in sys.argv:
    import sympy as sp

    x = sp.Symbol("x")
    polynomial = sp.Poly.from_list(zeta[::-1], x, domain=sp.ZZ)
    norm = sp.resultant(sp.cyclotomic_poly(p, x), polynomial.as_expr(), x)
    print("Exact resultant reduced modulo 37² =", norm % (p**2))
    assert norm % (p**2) == 37
