#!/usr/bin/env python3
"""Frozen QArena andcount generator, Python 3.10+ standard library only.
Run from qarena/: python3 -I solvers/andcount/solve.py mult-233 output.json
Small-field CPDs are polytof paper data (MIT, copyright 2026 Kirill Khoruzhii),
revision 0dcac107d15adc34dc646242d222f21ae7d32699:
https://github.com/ZIB-IOL/polytof ; paper arXiv:2602.15285, CC BY 4.0.
Their full MIT notice is retained below. Our CRT assembly, basis/trace choices,
scalar/Frobenius orbit search, and GF(16)-tower Toom implementation are original.
CRT follows the public task description and polynomial Chinese remaindering;
see Kim et al., ePrint 2022/1095, CC0, and the stated small-field constructions.
mult-283 reads the audited official verifier-bundle example, not a contestant
artifact, from https://qarena.ai/verifiers/bundle/andcount.zip . Its hash is
checked. The official example is not embedded or redistributed in this source.
All other instances are generated entirely from the code and MIT data below.
No network, subprocess, submission, token, or external solver module is used.
"""
import argparse
import json
import random
import hashlib
from pathlib import Path


POLYTOF_LICENSE = 'MIT License\n\nCopyright (c) 2026 Kirill Khoruzhii\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n'

SMALL_LIBRARY = {'10': {'polynomial': 1033,
        'triples': [[143, 143, 563],
                    [874, 874, 933],
                    [997, 997, 406],
                    [321, 321, 635],
                    [76, 76, 1018],
                    [269, 269, 385],
                    [557, 557, 748],
                    [574, 574, 455],
                    [19, 19, 811],
                    [633, 633, 104],
                    [934, 934, 448],
                    [479, 479, 424],
                    [648, 648, 606],
                    [920, 920, 316],
                    [272, 272, 866],
                    [671, 671, 900],
                    [848, 848, 228],
                    [463, 463, 864],
                    [880, 880, 578],
                    [2, 2, 802],
                    [882, 882, 352],
                    [495, 495, 740],
                    [850, 850, 678],
                    [701, 701, 66],
                    [421, 421, 207],
                    [968, 968, 169],
                    [621, 621, 102],
                    [746, 746, 347],
                    [700, 700, 832],
                    [86, 86, 539],
                    [847, 847, 911],
                    [372, 372, 690],
                    [571, 571, 317]]},
 '2': {'polynomial': 7, 'triples': [[1, 1, 3], [2, 2, 1], [3, 3, 2]]},
 '3': {'polynomial': 11, 'triples': [[1, 1, 7], [2, 2, 5], [4, 4, 1], [3, 3, 2], [5, 5, 4], [6, 6, 3]]},
 '4': {'polynomial': 19,
       'triples': [[1, 1, 9],
                   [12, 12, 3],
                   [13, 13, 10],
                   [14, 14, 1],
                   [8, 8, 6],
                   [6, 6, 7],
                   [15, 15, 14],
                   [4, 4, 2],
                   [11, 11, 12]]},
 '5': {'polynomial': 37,
       'triples': [[1, 1, 26],
                   [2, 2, 19],
                   [4, 4, 3],
                   [8, 8, 6],
                   [16, 16, 14],
                   [3, 3, 18],
                   [5, 5, 1],
                   [20, 20, 2],
                   [24, 24, 4],
                   [13, 13, 24],
                   [22, 22, 21],
                   [27, 27, 13],
                   [31, 31, 29]]},
 '6': {'polynomial': 67,
       'triples': [[55, 55, 17],
                   [32, 32, 25],
                   [23, 23, 8],
                   [37, 37, 57],
                   [26, 26, 15],
                   [63, 63, 54],
                   [47, 47, 45],
                   [46, 46, 4],
                   [1, 1, 41],
                   [61, 61, 63],
                   [20, 20, 19],
                   [41, 41, 44],
                   [34, 34, 3],
                   [38, 38, 14],
                   [4, 4, 13]]},
 '7': {'polynomial': 131,
       'triples': [[1, 1, 54],
                   [2, 2, 36],
                   [3, 3, 36],
                   [127, 127, 81],
                   [42, 42, 56],
                   [85, 85, 56],
                   [109, 109, 40],
                   [54, 54, 24],
                   [91, 91, 48],
                   [105, 105, 79],
                   [58, 58, 85],
                   [116, 116, 41],
                   [83, 83, 26],
                   [29, 29, 124],
                   [78, 78, 51],
                   [57, 57, 47],
                   [114, 114, 22],
                   [92, 92, 100],
                   [75, 75, 93],
                   [101, 101, 57],
                   [46, 46, 114],
                   [64, 64, 72]]},
 '8': {'polynomial': 285,
       'triples': [[35, 35, 34],
                   [102, 102, 76],
                   [69, 69, 110],
                   [31, 31, 72],
                   [42, 42, 21],
                   [53, 53, 93],
                   [23, 23, 221],
                   [142, 142, 147],
                   [153, 153, 78],
                   [97, 97, 53],
                   [116, 116, 162],
                   [21, 21, 151],
                   [205, 205, 98],
                   [124, 124, 175],
                   [177, 177, 205],
                   [209, 209, 229],
                   [78, 78, 107],
                   [159, 159, 142],
                   [125, 125, 156],
                   [70, 70, 167],
                   [59, 59, 59],
                   [129, 129, 79],
                   [12, 12, 10],
                   [141, 141, 69]]},
 '9': {'polynomial': 529,
       'triples': [[33, 33, 87],
                   [252, 252, 167],
                   [302, 302, 434],
                   [221, 221, 240],
                   [271, 271, 277],
                   [466, 466, 322],
                   [493, 493, 314],
                   [454, 454, 103],
                   [376, 376, 246],
                   [43, 43, 349],
                   [149, 149, 145],
                   [190, 190, 427],
                   [161, 161, 196],
                   [166, 166, 308],
                   [22, 22, 207],
                   [7, 7, 496],
                   [183, 183, 507],
                   [176, 176, 319],
                   [217, 217, 228],
                   [134, 134, 165],
                   [416, 416, 394],
                   [95, 95, 65],
                   [377, 377, 303],
                   [294, 294, 459],
                   [212, 212, 444],
                   [276, 276, 88],
                   [450, 450, 19],
                   [448, 448, 484],
                   [278, 278, 75],
                   [214, 214, 503]]}}

MODULI = {2: [2, 1, 0], 3: [3, 1, 0], 4: [4, 1, 0], 5: [5, 2, 0], 6: [6, 1, 0], 7: [7, 1, 0], 8: [8, 4, 3, 1, 0], 9: [9, 4, 0], 10: [10, 3, 0], 16: [16, 5, 3, 1, 0], 32: [32, 7, 3, 2, 0], 163: [163, 7, 6, 3, 0], 233: [233, 74, 0], 283: [283, 12, 7, 5, 0]}

def reduce_poly(v, p):
    degree = p.bit_length() - 1
    while v.bit_length() > degree:
        v ^= p << v.bit_length() - degree - 1
    return v

def transpose(columns, width):
    rows = [0] * width
    for j, column in enumerate(columns):
        while column:
            bit = column & -column
            rows[bit.bit_length() - 1] |= 1 << j
            column ^= bit
    return rows

def invert(rows):
    n = len(rows)
    a = [v | 1 << i << n for i, v in enumerate(rows)]
    for j in range(n):
        pivot = next((i for i in range(j, n) if a[i] >> j & 1))
        a[j], a[pivot] = (a[pivot], a[j])
        for i in range(n):
            if i != j and a[i] >> j & 1:
                a[i] ^= a[j]
    assert [v & (1 << n) - 1 for v in a] == [1 << i for i in range(n)]
    return [v >> n for v in a]

class Linear:

    def __init__(self, images):
        self.tables = []
        for offset in range(0, len(images), 8):
            table = [0] * 256
            for v in range(1, 256):
                bit = v & -v
                j = bit.bit_length() - 1
                table[v] = table[v ^ bit] ^ (images[offset + j] if offset + j < len(images) else 0)
            self.tables.append(table)

    def apply(self, v):
        out = 0
        for table in self.tables:
            out ^= table[v & 255]
            v >>= 8
        return out

    def many(self, rows):
        cache = {v: self.apply(v) for v in set(rows)}
        return [cache[v] for v in rows]

def decode(art):
    m = art['m']
    hexed = art.get('encoding') == 'hex-v1'
    parse = lambda s: int(s, 16) if hexed else int(s[::-1], 2)
    u = [parse(v) for v in art['U']]
    v = [parse(v) for v in art['V']]
    w = transpose([parse(s) for s in art['W']], len(u))
    return (m, u, v, w)

def encode(m, u, v, w):
    rank = len(u)
    hexed = m >= 163

    def fmt(value, width):
        return f'{value:0{(width + 3) // 4}x}' if hexed else f'{value:0{width}b}'[::-1]
    art = {'m': m}
    if hexed:
        art['encoding'] = 'hex-v1'
    art.update(U=[fmt(row, m) for row in u], V=[fmt(row, m) for row in v], W=[fmt(row, rank) for row in transpose(w, m)])
    return art

def xor_count(u, v, w):
    union = 0
    for column in w:
        union |= column
    return sum((x.bit_count() for x in u + v + w)) - sum((bool(x) for x in u + v)) - union.bit_count()

def karatsuba(m):

    def recursion(a, b):
        if len(a) == 1:
            return [(a[0], b[0], 1)] if a[0] and b[0] else []
        k = (len(a) + 1) // 2
        lo = recursion(a[:k], b[:k])
        hi = recursion(a[k:], b[k:])
        aa = [a[i] ^ (a[k + i] if k + i < len(a) else 0) for i in range(k)]
        bb = [b[i] ^ (b[k + i] if k + i < len(b) else 0) for i in range(k)]
        middle = recursion(aa, bb)
        return [(u, v, w ^ w << k) for u, v, w in lo] + [(u, v, w << k ^ w << 2 * k) for u, v, w in hi] + [(u, v, w << k) for u, v, w in middle]
    triples = recursion([1 << i for i in range(m)], [1 << i for i in range(m)])
    p = sum((1 << e for e in MODULI[m]))
    merged = {}
    for u, v, w in triples:
        merged[u, v] = merged.get((u, v), 0) ^ reduce_poly(w, p)
    triples = [(u, v, w) for (u, v), w in merged.items() if w]
    return encode(m, [x[0] for x in triples], [x[1] for x in triples], [x[2] for x in triples])

def gram(m, p):
    coefficients = [m - i for i in range(m) if p >> i & 1]
    powers = [m & 1] + [0] * (2 * m - 2)
    for k in range(1, len(powers)):
        value = k & 1 if k <= m and k in coefficients else 0
        for j in coefficients:
            if j < k or (k > m and j <= k):
                value ^= powers[k - j]
        powers[k] = value
    return [sum((powers[i + j] << j for j in range(m))) for i in range(m)]

def triality_transform(u, v, w, m, p, mode):
    if mode == 0:
        return (u.copy(), v.copy(), w.copy())
    rows = gram(m, p)
    to_dual = Linear(rows)
    from_dual = Linear(transpose(invert(rows), m))
    if mode == 1:
        return (to_dual.many(w), v.copy(), from_dual.many(u))
    if mode == 2:
        return (u.copy(), to_dual.many(w), from_dual.many(v))
    raise ValueError(mode)

def pmul(a, b):
    result = 0
    while b:
        bit = b & -b
        result ^= a << bit.bit_length() - 1
        b ^= bit
    return result

def quotient(a, b):
    q = 0
    d = b.bit_length()
    while a.bit_length() >= d:
        j = a.bit_length() - d
        a ^= b << j
        q ^= 1 << j
    assert a == 0
    return q

def inverse_poly(a, p):
    u, v = (a, p)
    x, y = (1, 0)
    while u != 1:
        if not u:
            raise ValueError('non-unit in CRT inverse')
        j = u.bit_length() - v.bit_length()
        if j < 0:
            u, v = (v, u)
            x, y = (y, x)
            j = -j
        u ^= v << j
        x ^= y << j
    return reduce_poly(x, p)

def gmultiply(a, b, p):
    return reduce_poly(pmul(a, b), p)

def gpower(a, e, p):
    out = 1
    while e:
        if e & 1:
            out = gmultiply(out, a, p)
        a = gmultiply(a, a, p)
        e >>= 1
    return out

def evaluate(poly, a, p):
    value = 0
    for i in reversed(range(poly.bit_length())):
        value = gmultiply(value, a, p) ^ poly >> i & 1
    return value

def irreducibles(d):
    out = []
    for p in range(1 << d | 1, 1 << d + 1, 2):
        reducible = False
        for k in range(1, d // 2 + 1):
            for divisor in range(1 << k | 1, 1 << k + 1, 2):
                if reduce_poly(p, divisor) == 0:
                    reducible = True
                    break
            if reducible:
                break
        if not reducible:
            out.append(p)
    return out

def truncated(k):
    triples = []
    for i in range(k):
        w = 1 << 2 * i if 2 * i < k else 0
        for j in range(k):
            if j != i and i + j < k:
                w ^= 1 << i + j
        triples.append((1 << i, 1 << i, w))
    for i in range(k):
        for j in range(i + 1, k):
            if i + j < k:
                triples.append((1 << i | 1 << j, 1 << i | 1 << j, 1 << i + j))
    return [t for t in triples if t[2]]

def ring4_truncated3(k=3):
    out = []
    for u, v, w in truncated(k):
        for a, b, c in [(1, 1, 3), (2, 2, 1), (3, 3, 2)]:
            embed = lambda value, scalar: sum((scalar << 2 * j for j in range(k) if value >> j & 1))
            out.append((embed(u, a), embed(v, b), embed(w, c)))
    return out

def choose_places(m, seed=0):
    rng = random.Random(seed)
    groups = []
    for tag in ['x', 'x1', 'infty']:
        opts = [(0, 0, None)]
        for k, r in enumerate([0, 1, 3, 5, 8, 11]):
            if k:
                opts.append((k, r, (tag, k)))
        groups.append(opts)
    groups.append([(0, 0, None), (2, 3, ('q2', 1)), (4, 9, ('q2', 2)), (6, 15, ('q2', 3))])
    ranks = {3: 6, 4: 9, 5: 13, 6: 15, 7: 22, 8: 24, 9: 30, 10: 33}
    for d in range(3, 11):
        polys = irreducibles(d)
        if seed:
            rng.shuffle(polys)
        groups += [[(0, 0, None), (d, ranks[d], ('field', p))] for p in polys]
    limit = 2 * m + 10
    dp = [10 ** 9] * (limit + 1)
    path = [None] * (limit + 1)
    dp[0] = 0
    for options in groups:
        new = dp.copy()
        np = path.copy()
        for degree, cost in enumerate(dp):
            if cost == 10 ** 9:
                continue
            for size, rank, place in options:
                if size and degree + size <= limit and (cost + rank < new[degree + size]):
                    new[degree + size] = cost + rank
                    np[degree + size] = (path[degree], place)
        dp, path = (new, np)
    degree = min(range(2 * m - 1, limit + 1), key=lambda d: (dp[d], d))
    places = []
    cursor = path[degree]
    while cursor:
        cursor, place = cursor
        places.append(place)
    return (places[::-1], dp[degree], degree)

def polynomial_place(place):
    tag, v = place
    if tag == 'field':
        return v
    if tag == 'x':
        return 1 << v
    if tag == 'x1':
        return pmul_power(3, v)
    if tag == 'q2':
        return pmul_power(7, v)
    if tag == 'infty':
        return None
    raise ValueError(place)

def pmul_power(a, e):
    out = 1
    for _ in range(e):
        out = pmul(out, a)
    return out

def basis_variants(place, library):
    tag, value = place
    q = polynomial_place(place)
    if tag == 'field':
        d = q.bit_length() - 1
        scheme = library[str(d)]
        srcpoly = scheme['polynomial']
        triples = [tuple(t) for t in scheme['triples']]
        roots = [a for a in range(1 << d) if evaluate(srcpoly, a, q) == 0]
        for root in roots:
            images = [1]
            for _ in range(1, d):
                images.append(gmultiply(images[-1], root, q))
            yield (triples, images, {'root': root})
    elif tag in ['x', 'x1']:
        k = value
        base = 2 if tag == 'x' else 3
        images = [1]
        for _ in range(1, k):
            images.append(gmultiply(images[-1], base, q))
        yield (truncated(k), images, {'coordinate': 'x' if tag == 'x' else 'x+1'})
    elif tag == 'q2':
        if value == 1:
            for a in [2, 3]:
                yield ([(1, 1, 3), (2, 2, 1), (3, 3, 2)], [1, a], {'root': a})
        elif value in [2, 3]:
            base_alpha = 2 ^ 7 ^ (pmul(7, 7) if value == 3 else 0)
            for alpha in [base_alpha, base_alpha ^ 1]:
                scalars = [0, 1, alpha, alpha ^ 1]
                for eta in scalars[1:]:
                    for lam in scalars if value == 3 else [0]:
                        t = gmultiply(eta, 7, q) ^ gmultiply(lam, pmul(7, 7), q)
                        images = []
                        for j in range(value):
                            base = gpower(t, j, q)
                            images += [base, gmultiply(base, alpha, q)]
                        yield (ring4_truncated3(value), images, {'root': alpha, 'eta': eta, 'lambda': lam})
        else:
            raise ValueError('q2^2 construction not selected in supported layouts')
    else:
        raise ValueError(place)

def construct_crt(m, seed=0, root_search=True, triality_search=True):
    library = SMALL_LIBRARY
    places, expected, total_degree = choose_places(m, seed)
    target = sum((1 << e for e in MODULI[m]))
    finite = [p for p in places if p[0] != 'infty']
    infinity = next((v for tag, v in places if tag == 'infty'), 0)
    modulus = 1
    for place in finite:
        modulus = pmul(modulus, polynomial_place(place))
    U = []
    V = []
    W = []
    details = []
    for place in finite:
        q = polynomial_place(place)
        degree = q.bit_length() - 1
        other = quotient(modulus, q)
        h = inverse_poly(reduce_poly(other, q), q)
        outputbasis = [reduce_poly(pmul(other, reduce_poly(h << j, q)), target) for j in range(degree)]
        residues = []
        value = 1
        for i in range(m):
            residues.append(value)
            value = reduce_poly(value << 1, q)
        inputembed = Linear(transpose(residues, degree))
        outputembed = Linear(outputbasis)
        best = None
        for triples, images, choice in basis_variants(place, library):
            invrows = invert(transpose(images, degree))
            to_inner = Linear(invrows)
            to_quotient = Linear(images)
            modes = [0, 1] if triality_search and place[0] == 'field' else [0]
            for mode in modes:
                local = triples
                if mode:
                    source_degree = degree
                    source_poly = library[str(degree)]['polynomial']
                    a, b, c = triality_transform(*map(list, zip(*triples)), source_degree, source_poly, mode)
                    local = list(zip(a, b, c))
                us = [inputembed.apply(to_inner.apply(u)) for u, v, w in local]
                vs = [inputembed.apply(to_inner.apply(v)) for u, v, w in local]
                ws = [outputembed.apply(to_quotient.apply(w)) for u, v, w in local]
                cost = sum((t.bit_count() for t in us + vs + ws))
                if best is None or cost < best[0]:
                    best = (cost, us, vs, ws, {**choice, 'triality': mode})
            if not root_search:
                break
        cost, us, vs, ws, choice = best
        U += us
        V += vs
        W += ws
        details.append({'place': place, 'degree': degree, 'rank': len(us), 'weight': cost, 'basis': choice})
    if infinity:
        outputs = [reduce_poly(1 << 2 * m - 2 - j ^ reduce_poly(1 << 2 * m - 2 - j, modulus), target) for j in range(infinity)]
        outputembed = Linear(outputs)

        def reverse_top(form):
            return sum((1 << m - 1 - j for j in range(infinity) if form >> j & 1))
        triples = truncated(infinity)
        U += [reverse_top(u) for u, v, w in triples]
        V += [reverse_top(v) for u, v, w in triples]
        W += [outputembed.apply(w) for u, v, w in triples]
        details.append({'place': ['infty', infinity], 'degree': infinity, 'rank': len(triples)})
    assert len(U) == expected
    return (encode(m, U, V, W), {'m': m, 'seed': seed, 'rank': len(U), 'xor': xor_count(U, V, W), 'total_degree': total_degree, 'finite_degree': modulus.bit_length() - 1, 'infinity': infinity, 'places': details, 'root_search': root_search, 'triality_search': triality_search, 'source': 'polytof 0dcac107d15adc34dc646242d222f21ae7d32699; small CPDs MIT'})

def construct_toom(m, seed=0):
    if m not in [16, 32]:
        raise ValueError('supported tower sizes: 16,32')
    rng = random.Random(seed)
    k = m // 4
    count = 2 * k - 1
    p = sum((1 << e for e in MODULI[m]))
    inner = SMALL_LIBRARY['4']
    q = inner['polynomial']
    triples = inner['triples']
    for candidate in range(2, 64):
        z = gpower(candidate, ((1 << m) - 1) // 15, p)
        if z not in [0, 1] and gpower(z, 15, p) == 1 and (gpower(z, 5, p) != 1) and (gpower(z, 3, p) != 1):
            break
    roots = [gpower(z, j, p) for j in range(15) if evaluate(q, gpower(z, j, p), p) == 0]
    alpha = roots[rng.randrange(len(roots))] if seed else roots[0]
    apow = [1]
    for _ in range(1, 4):
        apow.append(gmultiply(apow[-1], alpha, p))
    embed = Linear(apow)
    beta = 2 ^ (embed.apply(rng.randrange(16)) if seed else 0)
    images = []
    b = 1
    for _ in range(k):
        images += [gmultiply(a, b, p) for a in apow]
        b = gmultiply(b, beta, p)
    invrows = invert(transpose(images, m))
    inputmap = Linear(invrows)
    infinity = bool(seed % 2)
    points = list(range(16))
    if seed:
        rng.shuffle(points)
    points = points[:count - int(infinity)]
    contributions = []
    for t in points:
        numer = 1
        denom = 1
        for other in points:
            if other != t:
                numer = gmultiply(numer, beta ^ embed.apply(other), p)
                denom = gmultiply(denom, t ^ other, q)
        contributions.append(gmultiply(numer, embed.apply(gpower(denom, 14, q)), p))
    if infinity:
        c = gpower(beta, count - 1, p)
        for t, basis in zip(points, contributions):
            c ^= gmultiply(embed.apply(gpower(t, count - 1, q)), basis, p)
        contributions.append(c)
    labels = points + (['inf'] if infinity else [])
    U = []
    V = []
    W = []
    for label, basis in zip(labels, contributions):
        if label == 'inf':
            coefficient_images = [0] * (k - 1) + [1]
        else:
            coefficient_images = [1]
            for _ in range(1, k):
                coefficient_images.append(gmultiply(coefficient_images[-1], label, q))
        for u, v, w in triples:

            def lift(form):
                tower = 0
                for j, coef in enumerate(coefficient_images):
                    local = 0
                    for a in range(4):
                        local |= ((form & gmultiply(coef, 1 << a, q)).bit_count() & 1) << a
                    tower |= local << 4 * j
                return inputmap.apply(tower)
            U.append(lift(u))
            V.append(lift(v))
            W.append(gmultiply(embed.apply(w), basis, p))
    meta = {'m': m, 'seed': seed, 'rank': len(U), 'xor': xor_count(U, V, W), 'alpha': alpha, 'beta': beta, 'evaluation_points': labels, 'method': 'GF(16) tower, 2k-1 Toom evaluations, rank-9 inner products from MIT polytof data'}
    return (encode(m, U, V, W), meta)

def initial_field(m):
    d = SMALL_LIBRARY[str(m)]
    p = sum((1 << e for e in MODULI[m]))
    triples = d['triples']
    if d['polynomial'] == p:
        return [list(t) for t in zip(*triples)]
    root = next((a for a in range(1 << m) if evaluate(d['polynomial'], a, p) == 0))
    images = [1]
    for _ in range(1, m):
        images.append(gmultiply(images[-1], root, p))
    rowmap = Linear(invert(transpose(images, m)))
    outmap = Linear(images)
    return [[rowmap.apply(t[0]) for t in triples], [rowmap.apply(t[1]) for t in triples], [outmap.apply(t[2]) for t in triples]]

CASES = {'mult-10': {'frobenius': 7, 'm': 10, 'origin': 'small', 'scalars': [2, 2], 'triality': 0},
 'mult-16': {'frobenius': 0, 'm': 16, 'origin': 'toom', 'seed': 12, 'x_exponents': [-2, 0]},
 'mult-163': {'frobenius': 2,
              'm': 163,
              'origin': 'crt',
              'seed': 0,
              'triality_search': False,
              'x_exponents': [23, 24]},
 'mult-2': {'frobenius': 0, 'm': 2, 'origin': 'small', 'scalars': [1, 1], 'triality': 0},
 'mult-233': {'final_frobenius': 0,
              'frobenius': 0,
              'm': 233,
              'origin': 'crt',
              'seed': 11,
              'triality_search': True,
              'x_exponents': [-3, 1]},
 'mult-283': {'final_frobenius': 0,
              'frobenius': 3,
              'm': 283,
              'origin': 'official-example',
              'x_exponents': [123, 54]},
 'mult-3': {'frobenius': 0, 'm': 3, 'origin': 'small', 'scalars': [1, 1], 'triality': 0},
 'mult-32': {'frobenius': 31, 'm': 32, 'origin': 'toom', 'seed': 17, 'x_exponents': [0, 0]},
 'mult-4': {'frobenius': 0, 'm': 4, 'origin': 'karatsuba', 'x_exponents': [6, 0]},
 'mult-5': {'frobenius': 0, 'm': 5, 'origin': 'small', 'scalars': [1, 18], 'triality': 0},
 'mult-6': {'frobenius': 0, 'm': 6, 'origin': 'small', 'scalars': [6, 6], 'triality': 0},
 'mult-7': {'frobenius': 0, 'm': 7, 'origin': 'small', 'scalars': [20, 98], 'triality': 0},
 'mult-8': {'frobenius': 6, 'm': 8, 'origin': 'small', 'scalars': [62, 124], 'triality': 0},
 'mult-9': {'frobenius': 7, 'm': 9, 'origin': 'small', 'scalars': [475, 475], 'triality': 0}}

OFFICIAL_EXAMPLE_SHA256 = '22c06028353704ada7b20175f50e3d009805cb0a9e9d4361511c71be5811e69e'


def linear_power(images,power):
    result=[1<<i for i in range(len(images))]
    while power:
        step=Linear(images)
        if power&1:result=step.many(result)
        power>>=1
        if power:images=step.many(images)
    return Linear(result)


def frob_factors(m,u,v,w,power):
    if not power:return u,v,w
    p=sum(1<<e for e in MODULI[m]);columns=[reduce_poly(1<<(2*i),p) for i in range(m)];rows=transpose(columns,m)
    inputs=linear_power(rows,power);outputs=linear_power(transpose(invert(rows),m),power)
    return inputs.many(u),inputs.many(v),outputs.many(w)


def scalar_factors(m,u,v,w,left,right):
    if left==right==1:return u,v,w
    p=sum(1<<e for e in MODULI[m]);delta=inverse_poly(gmultiply(left,right,p),p)
    il=Linear(transpose([gmultiply(left,1<<j,p) for j in range(m)],m));ir=Linear(transpose([gmultiply(right,1<<j,p) for j in range(m)],m));ow=Linear([gmultiply(delta,1<<j,p) for j in range(m)])
    return il.many(u),ir.many(v),ow.many(w)


def solve(instance,official_example):
    case=CASES[instance];m=case['m'];p=sum(1<<e for e in MODULI[m]);origin=case['origin']
    if origin=='small':u,v,w=initial_field(m);u,v,w=triality_transform(u,v,w,m,p,case['triality'])
    elif origin=='karatsuba':_,u,v,w=decode(karatsuba(m))
    elif origin=='toom':artifact,_=construct_toom(m,case['seed']);_,u,v,w=decode(artifact)
    elif origin=='crt':artifact,_=construct_crt(m,case['seed'],True,case['triality_search']);_,u,v,w=decode(artifact)
    else:
        raw=official_example.read_bytes()
        if hashlib.sha256(raw).hexdigest()!=OFFICIAL_EXAMPLE_SHA256:raise ValueError('official example differs from the audited version; review before using')
        _,u,v,w=decode(json.loads(raw))
    u,v,w=frob_factors(m,u,v,w,case.get('frobenius',0))
    if 'scalars' in case:left,right=case['scalars']
    else:
        exponents=case.get('x_exponents',[0,0]);left,right=[gpower(2,e,p) if e>=0 else gpower(inverse_poly(2,p),-e,p) for e in exponents]
    u,v,w=scalar_factors(m,u,v,w,left,right)
    u,v,w=frob_factors(m,u,v,w,case.get('final_frobenius',0))
    return encode(m,u,v,w)


def main():
    parser=argparse.ArgumentParser();parser.add_argument('instance',choices=sorted(CASES));parser.add_argument('output',type=Path);parser.add_argument('--official-example',type=Path,default=Path('bundles/andcount/qarena-andcount/example/mult-283.json'));args=parser.parse_args()
    artifact=solve(args.instance,args.official_example);args.output.write_text(json.dumps(artifact,separators=(',',':')))
    _,u,v,w=decode(artifact);print(json.dumps({'r':len(u),'xor':xor_count(u,v,w)}))


if __name__=='__main__':main()
