Python+SQLite:小有限域多项式分解与精确乘回证书

10-20 5阅读

当多项式系数只剩有限个取值时,分解问题会呈现一种特别适合审计的形式:先找出所有不可约因子和重数,再把它们精确乘回去。本文用 Python 标准库实现一个有意限制规模的小型分解器,并把结果保存为可在 SQLite 中回放的证书。重点不是追赶大型计算机代数系统,而是看清域的前提、重因子的含义、停止条件以及验证边界。

运行环境为 Python 3.9 或更高版本,无需第三方包。九段代码都可分别复制为独立脚本运行,不依赖上一段留下的函数、变量或数据库。为此代码会重复少量基础函数。系数均为精确整数并在素数模数下运算,不使用浮点误差阈值。示例限定 p≤7、输入次数≤8,所有输出均由逐段独立运行获取。

Python+SQLite:小有限域多项式分解与精确乘回证书
AI概念图:重复部件表示因子重数,归档片表示可重新验算的记录;画面不承担数学证明。

一、先确定域、系数顺序和零的表示

我们只做素域 Fp,p 只允许取二到七之间的素数,也就是二、三、五、七。模九的整数环不是九元有限域,因此不能把参数改成九就宣称支持 F9;真正的扩域需要另一层不可约模多项式表示。限制参数是接口契约,不是对一般理论的限制。列表按常数项到最高次项排列,所以 [2, 0, 1] 表示 x²+2。负整数先取模,末尾零被删除,零统一为 [0],空列表也按零处理。最多输入九个整数系数,使后续八次以内的演示有明确边界。布尔值在 Python 中属于整数子类,但这里显式拒绝,避免 JSON 的 true 被悄悄当作系数一。内部乘除法接收已规范化列表;外部入口负责验证,而不是让每层循环重复检查。

from itertools import product
from math import isqrt

def prime(p):
    if type(p) is not int or not 2 <= p <= 7:
        raise ValueError("prime p must be in 2..7")
    if any(p % d == 0 for d in range(2, isqrt(p) + 1)):
        raise ValueError("p is composite")

def norm(a, p):
    if not isinstance(a, (list, tuple)) or len(a) > 9:
        raise ValueError("at most 9 integer coefficients")
    if any(type(x) is not int for x in a):
        raise ValueError("integer coefficients required")
    b = [x % p for x in a] or [0]
    while len(b) > 1 and b[-1] == 0:
        b.pop()
    return b

def trim(a):
    while len(a) > 1 and a[-1] == 0:
        a.pop()
    return a or [0]

def mul(a, b, p):
    c = [0] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        for j, y in enumerate(b):
            c[i + j] = (c[i + j] + x * y) % p
    return trim(c)

def divrem(a, b, p):
    if b == [0]:
        raise ZeroDivisionError("zero polynomial")
    r = a[:]
    q = [0] * max(1, len(a) - len(b) + 1)
    inverse = pow(b[-1], -1, p)
    while r != [0] and len(r) >= len(b):
        k = len(r) - len(b)
        c = r[-1] * inverse % p
        q[k] = c
        for j, x in enumerate(b):
            r[k + j] = (r[k + j] - c * x) % p
        trim(r)
    return trim(q), r


prime(5)
a = norm([-3, 5, 1, 0], 5)
b = norm([1, 1], 5)
print("normalized:", a)
print("product:", mul(a, b, 5))
print("division:", divrem(mul(a, b, 5), b, 5))
print("zero:", norm([], 5))
try:
    prime(4)
except ValueError as exc:
    print("rejected:", exc)

输出:

normalized: [2, 0, 1]
product: [2, 2, 1, 1]
division: ([2, 0, 1], [0])
zero: [0]
rejected: p is composite

二、按次数枚举首一因子,直到剩余部分不可约

完整分解写成一个非零常数单位乘以若干不同的首一不可约因子幂。先保存原多项式的首项系数,再把其余部分变为首一,能够避免把同一个因子的不同常数倍重复计算。算法依次枚举所有一次、二次等首一候选;某个候选能整除就连续除尽,除掉多少次便记录多少重。为什么可以直接收下候选?因为到达次数 d 时,所有更低次数的因子已经除尽;若当前候选可约,它必含更低次数因子,因而不可能再整除剩余多项式。若剩余次数小于二倍的下一候选次数,剩余部分若仍可约,就会存在不超过其次数一半的因子,与已穷尽的检查冲突。此处有意不用随机分裂,也不把试除包装成 Berlekamp 算法。

from itertools import product
from math import isqrt

def prime(p):
    if type(p) is not int or not 2 <= p <= 7:
        raise ValueError("prime p must be in 2..7")
    if any(p % d == 0 for d in range(2, isqrt(p) + 1)):
        raise ValueError("p is composite")

def norm(a, p):
    if not isinstance(a, (list, tuple)) or len(a) > 9:
        raise ValueError("at most 9 integer coefficients")
    if any(type(x) is not int for x in a):
        raise ValueError("integer coefficients required")
    b = [x % p for x in a] or [0]
    while len(b) > 1 and b[-1] == 0:
        b.pop()
    return b

def trim(a):
    while len(a) > 1 and a[-1] == 0:
        a.pop()
    return a or [0]

def mul(a, b, p):
    c = [0] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        for j, y in enumerate(b):
            c[i + j] = (c[i + j] + x * y) % p
    return trim(c)

def divrem(a, b, p):
    if b == [0]:
        raise ZeroDivisionError("zero polynomial")
    r = a[:]
    q = [0] * max(1, len(a) - len(b) + 1)
    inverse = pow(b[-1], -1, p)
    while r != [0] and len(r) >= len(b):
        k = len(r) - len(b)
        c = r[-1] * inverse % p
        q[k] = c
        for j, x in enumerate(b):
            r[k + j] = (r[k + j] - c * x) % p
        trim(r)
    return trim(q), r

def monics(p, d):
    for a in product(range(p), repeat=d):
        yield list(a) + [1]

def factor(a, p):
    prime(p)
    f = norm(a, p)
    if f == [0]:
        raise ValueError("zero has no finite factorization")
    unit = f[-1]
    f = [(x * pow(unit, -1, p)) % p for x in f]
    factors, d = [], 1
    while 2 * d <= len(f) - 1:
        for g in monics(p, d):
            e = 0
            while f != [1]:
                q, r = divrem(f, g, p)
                if r != [0]:
                    break
                f, e = q, e + 1
            if e:
                factors.append([g, e])
        d += 1
    if f != [1]:
        factors.append([f, 1])
    factors.sort(key=lambda ge: (len(ge[0]), ge[0]))
    return unit, factors

p = 5
f = mul([2], mul(mul([1, 1], [1, 1], p), [2, 0, 1], p), p)
print("f:", f)
print("unit and factors:", factor(f, p))
print("constant:", factor([3], p))
try:
    factor([0], p)
except ValueError as exc:
    print("zero:", exc)

输出:

f: [4, 3, 1, 4, 2]
unit and factors: (2, [[[1, 1], 2], [[2, 0, 1], 1]])
constant: (3, [])
zero: zero has no finite factorization

三、重因子不怕导数为零

正特征是最容易让有理数直觉出错的地方。在 F2 中,x⁴+x²+1 的形式导数为零,却显然不是常数,它等于二次不可约多项式 x²+x+1 的平方。导数为零意味着出现次数的指数都是特征的倍数;在素域中还可以通过压缩这些指数取 p 次根,完整平方自由算法需要处理这个分支。这里连续精确试除本来就会数出所有重数,不依赖导数是否非零,所以无需额外递归取根。示例同时给出非零导数的情况,说明只看导数是否为零既不能判断不可约,也不能完整判断平方自由。不要把 f 除以 gcd(f,f′) 直接当作任何特征下都正确的根基提取器;例如导数为零时那样做只会得到一。

from itertools import product
from math import isqrt

def prime(p):
    if type(p) is not int or not 2 <= p <= 7:
        raise ValueError("prime p must be in 2..7")
    if any(p % d == 0 for d in range(2, isqrt(p) + 1)):
        raise ValueError("p is composite")

def norm(a, p):
    if not isinstance(a, (list, tuple)) or len(a) > 9:
        raise ValueError("at most 9 integer coefficients")
    if any(type(x) is not int for x in a):
        raise ValueError("integer coefficients required")
    b = [x % p for x in a] or [0]
    while len(b) > 1 and b[-1] == 0:
        b.pop()
    return b

def trim(a):
    while len(a) > 1 and a[-1] == 0:
        a.pop()
    return a or [0]

def mul(a, b, p):
    c = [0] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        for j, y in enumerate(b):
            c[i + j] = (c[i + j] + x * y) % p
    return trim(c)

def divrem(a, b, p):
    if b == [0]:
        raise ZeroDivisionError("zero polynomial")
    r = a[:]
    q = [0] * max(1, len(a) - len(b) + 1)
    inverse = pow(b[-1], -1, p)
    while r != [0] and len(r) >= len(b):
        k = len(r) - len(b)
        c = r[-1] * inverse % p
        q[k] = c
        for j, x in enumerate(b):
            r[k + j] = (r[k + j] - c * x) % p
        trim(r)
    return trim(q), r

def monics(p, d):
    for a in product(range(p), repeat=d):
        yield list(a) + [1]

def factor(a, p):
    prime(p)
    f = norm(a, p)
    if f == [0]:
        raise ValueError("zero has no finite factorization")
    unit = f[-1]
    f = [(x * pow(unit, -1, p)) % p for x in f]
    factors, d = [], 1
    while 2 * d <= len(f) - 1:
        for g in monics(p, d):
            e = 0
            while f != [1]:
                q, r = divrem(f, g, p)
                if r != [0]:
                    break
                f, e = q, e + 1
            if e:
                factors.append([g, e])
        d += 1
    if f != [1]:
        factors.append([f, 1])
    factors.sort(key=lambda ge: (len(ge[0]), ge[0]))
    return unit, factors

def derivative(f, p):
    return trim([(i * f[i]) % p for i in range(1, len(f))])

for p, f in [(2, [1, 0, 1, 0, 1]), (3, [1, 2, 1])]:
    print("p, derivative:", p, derivative(f, p))
    print("factorization:", factor(f, p))

输出:

p, derivative: 2 [0]
factorization: (1, [[[1, 1, 1], 2]])
p, derivative: 3 [2, 2]
factorization: (1, [[[1, 1], 2]])

四、从完整分解整理平方自由层

平方自由分解与不可约分解是两个不同目标。把重数相同的不可约因子乘到一起,就得到互相互素的平方自由层;每一层内部可能仍有多个不可约因子。下面把重数一的 x 与 x+1 合成一个二次层,把重数三的 x²+x+1 放入另一层。层本身平方自由,并不意味着原多项式平方自由,判断原式只需查看所有记录的重数是否均为一。原式的根基是所有不同首一不可约因子各乘一次,非零单位通常不放入根基。我们的流程先完整分解再分组,逻辑最直观,但它不是更快的平方自由预处理;如果任务仅需要检测重根,直接计算导数及最大公因式更合适。

from itertools import product
from math import isqrt

def prime(p):
    if type(p) is not int or not 2 <= p <= 7:
        raise ValueError("prime p must be in 2..7")
    if any(p % d == 0 for d in range(2, isqrt(p) + 1)):
        raise ValueError("p is composite")

def norm(a, p):
    if not isinstance(a, (list, tuple)) or len(a) > 9:
        raise ValueError("at most 9 integer coefficients")
    if any(type(x) is not int for x in a):
        raise ValueError("integer coefficients required")
    b = [x % p for x in a] or [0]
    while len(b) > 1 and b[-1] == 0:
        b.pop()
    return b

def trim(a):
    while len(a) > 1 and a[-1] == 0:
        a.pop()
    return a or [0]

def mul(a, b, p):
    c = [0] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        for j, y in enumerate(b):
            c[i + j] = (c[i + j] + x * y) % p
    return trim(c)

def divrem(a, b, p):
    if b == [0]:
        raise ZeroDivisionError("zero polynomial")
    r = a[:]
    q = [0] * max(1, len(a) - len(b) + 1)
    inverse = pow(b[-1], -1, p)
    while r != [0] and len(r) >= len(b):
        k = len(r) - len(b)
        c = r[-1] * inverse % p
        q[k] = c
        for j, x in enumerate(b):
            r[k + j] = (r[k + j] - c * x) % p
        trim(r)
    return trim(q), r

def monics(p, d):
    for a in product(range(p), repeat=d):
        yield list(a) + [1]

def factor(a, p):
    prime(p)
    f = norm(a, p)
    if f == [0]:
        raise ValueError("zero has no finite factorization")
    unit = f[-1]
    f = [(x * pow(unit, -1, p)) % p for x in f]
    factors, d = [], 1
    while 2 * d <= len(f) - 1:
        for g in monics(p, d):
            e = 0
            while f != [1]:
                q, r = divrem(f, g, p)
                if r != [0]:
                    break
                f, e = q, e + 1
            if e:
                factors.append([g, e])
        d += 1
    if f != [1]:
        factors.append([f, 1])
    factors.sort(key=lambda ge: (len(ge[0]), ge[0]))
    return unit, factors

p = 2
f = mul([0, 1], [1, 1], p)
for _ in range(3):
    f = mul(f, [1, 1, 1], p)
u, fs = factor(f, p)
layers, radical = {}, [1]
for g, e in fs:
    layers[e] = mul(layers.get(e, [1]), g, p)
    radical = mul(radical, g, p)
print("f:", f)
print("layers:", sorted(layers.items()))
print("radical:", radical)
print("squarefree:", all(e == 1 for g, e in fs))

输出:

f: [0, 1, 0, 1, 1, 1, 1, 0, 1]
layers: [(1, [0, 1, 1]), (3, [1, 1, 1])]
radical: [0, 1, 0, 0, 1]
squarefree: False

五、用 Frobenius 判据交叉检查不可约性

试除容易解释,但不能让所有测试都只复述同一算法。另一条路线来自有限域恒等式:x 的 p 的 k 次方减 x,是所有次数整除 k 的首一不可约多项式之积,而且没有重复因子。对一个 n 次首一多项式,逐次计算 x、xᵖ、xᵖ² 等在模该多项式后的余数;对一到 n 的一半做最大公因式排除,再检查第 n 次迭代回到 x,就能判定不可约。这里采用检查全部小次数的简单版本,没做只检查 n 的素因子那种优化。运算始终约减,避免显式生成巨大指数对应的稠密多项式。它适合作为不同思路的交叉检查,但本例仍共享基础乘除运算,不能声称实现层面完全独立。最后一节另用不调用除法的乘积枚举做独立小域核对。

from itertools import product
from math import isqrt

def prime(p):
    if type(p) is not int or not 2 <= p <= 7:
        raise ValueError("prime p must be in 2..7")
    if any(p % d == 0 for d in range(2, isqrt(p) + 1)):
        raise ValueError("p is composite")

def norm(a, p):
    if not isinstance(a, (list, tuple)) or len(a) > 9:
        raise ValueError("at most 9 integer coefficients")
    if any(type(x) is not int for x in a):
        raise ValueError("integer coefficients required")
    b = [x % p for x in a] or [0]
    while len(b) > 1 and b[-1] == 0:
        b.pop()
    return b

def trim(a):
    while len(a) > 1 and a[-1] == 0:
        a.pop()
    return a or [0]

def mul(a, b, p):
    c = [0] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        for j, y in enumerate(b):
            c[i + j] = (c[i + j] + x * y) % p
    return trim(c)

def divrem(a, b, p):
    if b == [0]:
        raise ZeroDivisionError("zero polynomial")
    r = a[:]
    q = [0] * max(1, len(a) - len(b) + 1)
    inverse = pow(b[-1], -1, p)
    while r != [0] and len(r) >= len(b):
        k = len(r) - len(b)
        c = r[-1] * inverse % p
        q[k] = c
        for j, x in enumerate(b):
            r[k + j] = (r[k + j] - c * x) % p
        trim(r)
    return trim(q), r

def monics(p, d):
    for a in product(range(p), repeat=d):
        yield list(a) + [1]

def factor(a, p):
    prime(p)
    f = norm(a, p)
    if f == [0]:
        raise ValueError("zero has no finite factorization")
    unit = f[-1]
    f = [(x * pow(unit, -1, p)) % p for x in f]
    factors, d = [], 1
    while 2 * d <= len(f) - 1:
        for g in monics(p, d):
            e = 0
            while f != [1]:
                q, r = divrem(f, g, p)
                if r != [0]:
                    break
                f, e = q, e + 1
            if e:
                factors.append([g, e])
        d += 1
    if f != [1]:
        factors.append([f, 1])
    factors.sort(key=lambda ge: (len(ge[0]), ge[0]))
    return unit, factors

def gcd_poly(a, b, p):
    while b != [0]:
        a, b = b, divrem(a, b, p)[1]
    return [(v * pow(a[-1], -1, p)) % p for v in a]

def power_mod(a, e, f, p):
    r = [1]
    while e:
        if e % 2:
            r = divrem(mul(r, a, p), f, p)[1]
        a = divrem(mul(a, a, p), f, p)[1]
        e //= 2
    return r

def frobenius_irred(f, p):
    prime(p)
    f = norm(f, p)
    n = len(f) - 1
    if n < 1 or f[-1] != 1:
        return False
    x = divrem([0, 1], f, p)[1]
    h = x
    for k in range(1, n + 1):
        h = power_mod(h, p, f, p)
        z = [0] * max(len(h), len(x))
        for i, v in enumerate(h):
            z[i] += v
        for i, v in enumerate(x):
            z[i] -= v
        z = trim([v % p for v in z])
        if k <= n // 2 and gcd_poly(f, z, p) != [1]:
            return False
    return h == x

for f in ([1, 1, 0, 0, 1], [1, 0, 1, 0, 1], [0, 1]):
    print(f, frobenius_irred(f, 2))

输出:

[1, 1, 0, 0, 1] True
[1, 0, 1, 0, 1] False
[0, 1] True

六、乘回原式只是证书的第一层

一个只存因子数组的结果可以精确乘回去,但这还不能证明分解已经完成:直接把整个可约原式当作一个因子,乘积仍然正确。验证器必须同时检查域、规范系数、非零单位、正整数重数、因子互异、每个因子不可约以及总次数,最后才把各项精确相乘。下面证书含原式副本,但验证时另传可信的原始输入和模数;否则攻击者同时改掉原式及因子,内部自洽也会被误当成正确。我们允许因子顺序变化,因为乘法交换律保证它不影响数学意义;生产器为了展示稳定才排序。常数证书含空因子列表,空积为一;零没有这样的有限分解,直接拒绝。这个验证器是有资源上界的教学接口,不承诺接受任意对象协议或无限大的恶意输入。

from itertools import product
from math import isqrt

def prime(p):
    if type(p) is not int or not 2 <= p <= 7:
        raise ValueError("prime p must be in 2..7")
    if any(p % d == 0 for d in range(2, isqrt(p) + 1)):
        raise ValueError("p is composite")

def norm(a, p):
    if not isinstance(a, (list, tuple)) or len(a) > 9:
        raise ValueError("at most 9 integer coefficients")
    if any(type(x) is not int for x in a):
        raise ValueError("integer coefficients required")
    b = [x % p for x in a] or [0]
    while len(b) > 1 and b[-1] == 0:
        b.pop()
    return b

def trim(a):
    while len(a) > 1 and a[-1] == 0:
        a.pop()
    return a or [0]

def mul(a, b, p):
    c = [0] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        for j, y in enumerate(b):
            c[i + j] = (c[i + j] + x * y) % p
    return trim(c)

def divrem(a, b, p):
    if b == [0]:
        raise ZeroDivisionError("zero polynomial")
    r = a[:]
    q = [0] * max(1, len(a) - len(b) + 1)
    inverse = pow(b[-1], -1, p)
    while r != [0] and len(r) >= len(b):
        k = len(r) - len(b)
        c = r[-1] * inverse % p
        q[k] = c
        for j, x in enumerate(b):
            r[k + j] = (r[k + j] - c * x) % p
        trim(r)
    return trim(q), r

def monics(p, d):
    for a in product(range(p), repeat=d):
        yield list(a) + [1]

def factor(a, p):
    prime(p)
    f = norm(a, p)
    if f == [0]:
        raise ValueError("zero has no finite factorization")
    unit = f[-1]
    f = [(x * pow(unit, -1, p)) % p for x in f]
    factors, d = [], 1
    while 2 * d <= len(f) - 1:
        for g in monics(p, d):
            e = 0
            while f != [1]:
                q, r = divrem(f, g, p)
                if r != [0]:
                    break
                f, e = q, e + 1
            if e:
                factors.append([g, e])
        d += 1
    if f != [1]:
        factors.append([f, 1])
    factors.sort(key=lambda ge: (len(ge[0]), ge[0]))
    return unit, factors

def irreducible(g, p):
    if len(g) < 2 or g[-1] != 1:
        return False
    return all(divrem(g, h, p)[1] != [0]
               for d in range(1, (len(g) - 1) // 2 + 1)
               for h in monics(p, d))

def certificate(f, p):
    u, fs = factor(f, p)
    return {"p": p, "f": norm(f, p), "unit": u, "factors": fs}

def verify(c, expected_p, expected_f):
    try:
        prime(expected_p)
        f = norm(expected_f, expected_p)
        if f == [0] or type(c) is not dict:
            return False
        if set(c) != {"p", "f", "unit", "factors"}:
            return False
        p, u, fs = c["p"], c["unit"], c["factors"]
        if type(p) is not int or p != expected_p:
            return False
        if type(c["f"]) is not list or c["f"] != f:
            return False
        if any(type(x) is not int for x in c["f"]):
            return False
        if type(u) is not int or not 1 <= u < p:
            return False
        if type(fs) is not list or len(fs) > 8:
            return False
        seen, degree, rebuilt = set(), 0, [u]
        for item in fs:
            if type(item) is not list or len(item) != 2:
                return False
            g, e = item
            if type(g) is not list or norm(g, p) != g:
                return False
            if type(e) is not int or not 1 <= e <= 8:
                return False
            if tuple(g) in seen or not irreducible(g, p):
                return False
            seen.add(tuple(g))
            degree += (len(g) - 1) * e
            if degree > len(f) - 1:
                return False
            for _ in range(e):
                rebuilt = mul(rebuilt, g, p)
        return degree == len(f) - 1 and rebuilt == f
    except (ValueError, TypeError, KeyError, ZeroDivisionError):
        return False

from copy import deepcopy
f, p = [1, 0, 1, 0, 1], 2
c = certificate(f, p)
print("valid:", verify(c, p, f))
bad = deepcopy(c)
bad["factors"] = [[f, 1]]
print("unsplit:", verify(bad, p, f))
bad = deepcopy(c)
bad["factors"][0][1] = 1
print("wrong exponent:", verify(bad, p, f))
print("constant:", verify(certificate([3], 5), 5, [3]))

输出:

valid: True
unsplit: False
wrong exponent: False
constant: True

七、把证书存进 SQLite,再从查询结果验证

数据库负责保存结果,不负责证明代数结论。这里用一张主键加 JSON 文本的表保留证书,结构简单,适合复现一个独立运算;若要统计因子频率,再拆出因子明细表也不迟。SQL 参数一律用占位符,避免把多项式或标识符拼成 SQL。写入放进连接的事务上下文,正常退出提交、异常回滚;这个上下文本身不会关闭连接,因此例子最后显式关闭。回放先按主键查询,再限制文本长度并解析 JSON,然后使用外部传入的期望输入验证。长度门槛并不是完整的安全沙箱,文件来源、权限和服务层资源配额仍需额外管理。保存后读出的内容必须重新验算,不能只因为它来自本地数据库就跳过检查。

from itertools import product
from math import isqrt

def prime(p):
    if type(p) is not int or not 2 <= p <= 7:
        raise ValueError("prime p must be in 2..7")
    if any(p % d == 0 for d in range(2, isqrt(p) + 1)):
        raise ValueError("p is composite")

def norm(a, p):
    if not isinstance(a, (list, tuple)) or len(a) > 9:
        raise ValueError("at most 9 integer coefficients")
    if any(type(x) is not int for x in a):
        raise ValueError("integer coefficients required")
    b = [x % p for x in a] or [0]
    while len(b) > 1 and b[-1] == 0:
        b.pop()
    return b

def trim(a):
    while len(a) > 1 and a[-1] == 0:
        a.pop()
    return a or [0]

def mul(a, b, p):
    c = [0] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        for j, y in enumerate(b):
            c[i + j] = (c[i + j] + x * y) % p
    return trim(c)

def divrem(a, b, p):
    if b == [0]:
        raise ZeroDivisionError("zero polynomial")
    r = a[:]
    q = [0] * max(1, len(a) - len(b) + 1)
    inverse = pow(b[-1], -1, p)
    while r != [0] and len(r) >= len(b):
        k = len(r) - len(b)
        c = r[-1] * inverse % p
        q[k] = c
        for j, x in enumerate(b):
            r[k + j] = (r[k + j] - c * x) % p
        trim(r)
    return trim(q), r

def monics(p, d):
    for a in product(range(p), repeat=d):
        yield list(a) + [1]

def factor(a, p):
    prime(p)
    f = norm(a, p)
    if f == [0]:
        raise ValueError("zero has no finite factorization")
    unit = f[-1]
    f = [(x * pow(unit, -1, p)) % p for x in f]
    factors, d = [], 1
    while 2 * d <= len(f) - 1:
        for g in monics(p, d):
            e = 0
            while f != [1]:
                q, r = divrem(f, g, p)
                if r != [0]:
                    break
                f, e = q, e + 1
            if e:
                factors.append([g, e])
        d += 1
    if f != [1]:
        factors.append([f, 1])
    factors.sort(key=lambda ge: (len(ge[0]), ge[0]))
    return unit, factors

def irreducible(g, p):
    if len(g) < 2 or g[-1] != 1:
        return False
    return all(divrem(g, h, p)[1] != [0]
               for d in range(1, (len(g) - 1) // 2 + 1)
               for h in monics(p, d))

def certificate(f, p):
    u, fs = factor(f, p)
    return {"p": p, "f": norm(f, p), "unit": u, "factors": fs}

def verify(c, expected_p, expected_f):
    try:
        prime(expected_p)
        f = norm(expected_f, expected_p)
        if f == [0] or type(c) is not dict:
            return False
        if set(c) != {"p", "f", "unit", "factors"}:
            return False
        p, u, fs = c["p"], c["unit"], c["factors"]
        if type(p) is not int or p != expected_p:
            return False
        if type(c["f"]) is not list or c["f"] != f:
            return False
        if any(type(x) is not int for x in c["f"]):
            return False
        if type(u) is not int or not 1 <= u < p:
            return False
        if type(fs) is not list or len(fs) > 8:
            return False
        seen, degree, rebuilt = set(), 0, [u]
        for item in fs:
            if type(item) is not list or len(item) != 2:
                return False
            g, e = item
            if type(g) is not list or norm(g, p) != g:
                return False
            if type(e) is not int or not 1 <= e <= 8:
                return False
            if tuple(g) in seen or not irreducible(g, p):
                return False
            seen.add(tuple(g))
            degree += (len(g) - 1) * e
            if degree > len(f) - 1:
                return False
            for _ in range(e):
                rebuilt = mul(rebuilt, g, p)
        return degree == len(f) - 1 and rebuilt == f
    except (ValueError, TypeError, KeyError, ZeroDivisionError):
        return False

import json
import sqlite3

def save(con, key, c):
    blob = json.dumps(c, separators=(",", ":"), sort_keys=True)
    con.execute("INSERT INTO cert VALUES (?, ?)", (key, blob))

def replay(con, key, p, f):
    row = con.execute("SELECT payload FROM cert WHERE id=?", (key,)).fetchone()
    if row is None or type(row[0]) is not str or len(row[0]) > 10000:
        return False
    try:
        c = json.loads(row[0])
    except (ValueError, RecursionError):
        return False
    return verify(c, p, f)

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE cert(id TEXT PRIMARY KEY, payload TEXT NOT NULL)")
f = [1, 0, 1, 0, 1]
with con:
    save(con, "case-2", certificate(f, 2))
print("rows:", con.execute("SELECT count(*) FROM cert").fetchone()[0])
print("replay:", replay(con, "case-2", 2, f))
print("missing:", replay(con, "missing", 2, f))
con.close()

输出:

rows: 1
replay: True
missing: False

八、篡改演练必须发生在持久化边界

只修改内存里的对象不足以覆盖存储链路。下面真实更新数据库中的 JSON 文本,依次制造错误重数、错误模数、未拆分的可约因子、重复因子、布尔重数和损坏 JSON,每一次都从查询入口重新验证。演练还会制造一份内部完全正确、却属于另一个原式的证书,以确认验证器与可信请求绑定。这里的证书提供可重算的数学正确性,不是数字签名,不证明是谁写入,也不能检测攻击者把证书与外部可信输入一起替换的情况。若业务需要来源真实性或防回滚,需要独立维护签名、访问控制或可信日志;不要把 JSON 序列化稳定、哈希相同或乘积正确误称为防篡改认证。

from itertools import product
from math import isqrt

def prime(p):
    if type(p) is not int or not 2 <= p <= 7:
        raise ValueError("prime p must be in 2..7")
    if any(p % d == 0 for d in range(2, isqrt(p) + 1)):
        raise ValueError("p is composite")

def norm(a, p):
    if not isinstance(a, (list, tuple)) or len(a) > 9:
        raise ValueError("at most 9 integer coefficients")
    if any(type(x) is not int for x in a):
        raise ValueError("integer coefficients required")
    b = [x % p for x in a] or [0]
    while len(b) > 1 and b[-1] == 0:
        b.pop()
    return b

def trim(a):
    while len(a) > 1 and a[-1] == 0:
        a.pop()
    return a or [0]

def mul(a, b, p):
    c = [0] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        for j, y in enumerate(b):
            c[i + j] = (c[i + j] + x * y) % p
    return trim(c)

def divrem(a, b, p):
    if b == [0]:
        raise ZeroDivisionError("zero polynomial")
    r = a[:]
    q = [0] * max(1, len(a) - len(b) + 1)
    inverse = pow(b[-1], -1, p)
    while r != [0] and len(r) >= len(b):
        k = len(r) - len(b)
        c = r[-1] * inverse % p
        q[k] = c
        for j, x in enumerate(b):
            r[k + j] = (r[k + j] - c * x) % p
        trim(r)
    return trim(q), r

def monics(p, d):
    for a in product(range(p), repeat=d):
        yield list(a) + [1]

def factor(a, p):
    prime(p)
    f = norm(a, p)
    if f == [0]:
        raise ValueError("zero has no finite factorization")
    unit = f[-1]
    f = [(x * pow(unit, -1, p)) % p for x in f]
    factors, d = [], 1
    while 2 * d <= len(f) - 1:
        for g in monics(p, d):
            e = 0
            while f != [1]:
                q, r = divrem(f, g, p)
                if r != [0]:
                    break
                f, e = q, e + 1
            if e:
                factors.append([g, e])
        d += 1
    if f != [1]:
        factors.append([f, 1])
    factors.sort(key=lambda ge: (len(ge[0]), ge[0]))
    return unit, factors

def irreducible(g, p):
    if len(g) < 2 or g[-1] != 1:
        return False
    return all(divrem(g, h, p)[1] != [0]
               for d in range(1, (len(g) - 1) // 2 + 1)
               for h in monics(p, d))

def certificate(f, p):
    u, fs = factor(f, p)
    return {"p": p, "f": norm(f, p), "unit": u, "factors": fs}

def verify(c, expected_p, expected_f):
    try:
        prime(expected_p)
        f = norm(expected_f, expected_p)
        if f == [0] or type(c) is not dict:
            return False
        if set(c) != {"p", "f", "unit", "factors"}:
            return False
        p, u, fs = c["p"], c["unit"], c["factors"]
        if type(p) is not int or p != expected_p:
            return False
        if type(c["f"]) is not list or c["f"] != f:
            return False
        if any(type(x) is not int for x in c["f"]):
            return False
        if type(u) is not int or not 1 <= u < p:
            return False
        if type(fs) is not list or len(fs) > 8:
            return False
        seen, degree, rebuilt = set(), 0, [u]
        for item in fs:
            if type(item) is not list or len(item) != 2:
                return False
            g, e = item
            if type(g) is not list or norm(g, p) != g:
                return False
            if type(e) is not int or not 1 <= e <= 8:
                return False
            if tuple(g) in seen or not irreducible(g, p):
                return False
            seen.add(tuple(g))
            degree += (len(g) - 1) * e
            if degree > len(f) - 1:
                return False
            for _ in range(e):
                rebuilt = mul(rebuilt, g, p)
        return degree == len(f) - 1 and rebuilt == f
    except (ValueError, TypeError, KeyError, ZeroDivisionError):
        return False

import json
import sqlite3

def save(con, key, c):
    blob = json.dumps(c, separators=(",", ":"), sort_keys=True)
    con.execute("INSERT INTO cert VALUES (?, ?)", (key, blob))

def replay(con, key, p, f):
    row = con.execute("SELECT payload FROM cert WHERE id=?", (key,)).fetchone()
    if row is None or type(row[0]) is not str or len(row[0]) > 10000:
        return False
    try:
        c = json.loads(row[0])
    except (ValueError, RecursionError):
        return False
    return verify(c, p, f)

from copy import deepcopy
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE cert(id TEXT PRIMARY KEY, payload TEXT NOT NULL)")
f, p = [1, 0, 1, 0, 1], 2
c = certificate(f, p)
with con:
    save(con, "test", c)
trials = []
b = deepcopy(c); b["factors"][0][1] = 1
trials.append(("exponent", b))
b = deepcopy(c); b["p"] = 3
trials.append(("modulus", b))
b = deepcopy(c); b["factors"] = [[f, 1]]
trials.append(("unsplit", b))
b = deepcopy(c); b["factors"] = [[[1, 1, 1], 1], [[1, 1, 1], 1]]
trials.append(("duplicate", b))
b = deepcopy(c); b["factors"][0][1] = True
trials.append(("boolean", b))
trials.append(("other input", certificate([1, 1], 2)))
for label, bad in trials:
    with con:
        con.execute("UPDATE cert SET payload=? WHERE id=?", (json.dumps(bad), "test"))
    print(label + ":", replay(con, "test", p, f))
with con:
    con.execute("UPDATE cert SET payload=? WHERE id=?", ("{broken", "test"))
print("broken JSON:", replay(con, "test", p, f))
con.close()

输出:

exponent: False
modulus: False
unsplit: False
duplicate: False
boolean: False
other input: False
broken JSON: False

九、独立乘积枚举与关闭后磁盘回放

最后不用被测除法来判定小多项式是否可约。测试先按次数建立所有首一多项式集合,通过另写的卷积乘法枚举两个非平凡首一多项式的乘积;落在乘积集合中的多项式就是可约的,剩余项组成不可约库。随后以不可约因子的非递减组合生成每一个首一多项式的期望分解,重复出现次数直接给出重数。这样核对了 F2 中一到五次、F3 中一到四次的全部首一多项式,不只抽查几个漂亮例子。每个测试还乘上所有非零单位,覆盖非首一输入;常数另行核对。示例随后创建临时磁盘数据库,提交、关闭并重新打开,验证真实磁盘回放,而不是把内存连接换个变量名。临时目录离开上下文会清理,便于每段代码独立重复运行。有限范围的穷举不能代替一般证明,但能有效暴露系数方向、重数累计、单位丢失和停止条件的错误。

from itertools import product
from math import isqrt

def prime(p):
    if type(p) is not int or not 2 <= p <= 7:
        raise ValueError("prime p must be in 2..7")
    if any(p % d == 0 for d in range(2, isqrt(p) + 1)):
        raise ValueError("p is composite")

def norm(a, p):
    if not isinstance(a, (list, tuple)) or len(a) > 9:
        raise ValueError("at most 9 integer coefficients")
    if any(type(x) is not int for x in a):
        raise ValueError("integer coefficients required")
    b = [x % p for x in a] or [0]
    while len(b) > 1 and b[-1] == 0:
        b.pop()
    return b

def trim(a):
    while len(a) > 1 and a[-1] == 0:
        a.pop()
    return a or [0]

def mul(a, b, p):
    c = [0] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        for j, y in enumerate(b):
            c[i + j] = (c[i + j] + x * y) % p
    return trim(c)

def divrem(a, b, p):
    if b == [0]:
        raise ZeroDivisionError("zero polynomial")
    r = a[:]
    q = [0] * max(1, len(a) - len(b) + 1)
    inverse = pow(b[-1], -1, p)
    while r != [0] and len(r) >= len(b):
        k = len(r) - len(b)
        c = r[-1] * inverse % p
        q[k] = c
        for j, x in enumerate(b):
            r[k + j] = (r[k + j] - c * x) % p
        trim(r)
    return trim(q), r

def monics(p, d):
    for a in product(range(p), repeat=d):
        yield list(a) + [1]

def factor(a, p):
    prime(p)
    f = norm(a, p)
    if f == [0]:
        raise ValueError("zero has no finite factorization")
    unit = f[-1]
    f = [(x * pow(unit, -1, p)) % p for x in f]
    factors, d = [], 1
    while 2 * d <= len(f) - 1:
        for g in monics(p, d):
            e = 0
            while f != [1]:
                q, r = divrem(f, g, p)
                if r != [0]:
                    break
                f, e = q, e + 1
            if e:
                factors.append([g, e])
        d += 1
    if f != [1]:
        factors.append([f, 1])
    factors.sort(key=lambda ge: (len(ge[0]), ge[0]))
    return unit, factors

def irreducible(g, p):
    if len(g) < 2 or g[-1] != 1:
        return False
    return all(divrem(g, h, p)[1] != [0]
               for d in range(1, (len(g) - 1) // 2 + 1)
               for h in monics(p, d))

def certificate(f, p):
    u, fs = factor(f, p)
    return {"p": p, "f": norm(f, p), "unit": u, "factors": fs}

def verify(c, expected_p, expected_f):
    try:
        prime(expected_p)
        f = norm(expected_f, expected_p)
        if f == [0] or type(c) is not dict:
            return False
        if set(c) != {"p", "f", "unit", "factors"}:
            return False
        p, u, fs = c["p"], c["unit"], c["factors"]
        if type(p) is not int or p != expected_p:
            return False
        if type(c["f"]) is not list or c["f"] != f:
            return False
        if any(type(x) is not int for x in c["f"]):
            return False
        if type(u) is not int or not 1 <= u < p:
            return False
        if type(fs) is not list or len(fs) > 8:
            return False
        seen, degree, rebuilt = set(), 0, [u]
        for item in fs:
            if type(item) is not list or len(item) != 2:
                return False
            g, e = item
            if type(g) is not list or norm(g, p) != g:
                return False
            if type(e) is not int or not 1 <= e <= 8:
                return False
            if tuple(g) in seen or not irreducible(g, p):
                return False
            seen.add(tuple(g))
            degree += (len(g) - 1) * e
            if degree > len(f) - 1:
                return False
            for _ in range(e):
                rebuilt = mul(rebuilt, g, p)
        return degree == len(f) - 1 and rebuilt == f
    except (ValueError, TypeError, KeyError, ZeroDivisionError):
        return False

import json
import sqlite3

def save(con, key, c):
    blob = json.dumps(c, separators=(",", ":"), sort_keys=True)
    con.execute("INSERT INTO cert VALUES (?, ?)", (key, blob))

def replay(con, key, p, f):
    row = con.execute("SELECT payload FROM cert WHERE id=?", (key,)).fetchone()
    if row is None or type(row[0]) is not str or len(row[0]) > 10000:
        return False
    try:
        c = json.loads(row[0])
    except (ValueError, RecursionError):
        return False
    return verify(c, p, f)

from collections import Counter
from itertools import combinations_with_replacement
from pathlib import Path
from tempfile import TemporaryDirectory

def independent_mul(a, b, p):
    return tuple(sum(a[i] * b[k-i] for i in range(len(a))
                     if 0 <= k-i < len(b)) % p
                 for k in range(len(a) + len(b) - 1))

checked = 0
for p, limit in [(2, 5), (3, 4)]:
    by_degree = {d: [tuple(a) + (1,) for a in product(range(p), repeat=d)]
                 for d in range(1, limit + 1)}
    irreducibles = []
    for d in range(1, limit + 1):
        reducibles = set()
        for k in range(1, d // 2 + 1):
            for a in by_degree[k]:
                for b in by_degree[d-k]:
                    reducibles.add(independent_mul(a, b, p))
        irreducibles += [a for a in by_degree[d] if a not in reducibles]
    expected = {}
    def extend(value, start, chosen):
        if len(value) > 1:
            expected[value] = Counter(chosen)
        for j in range(start, len(irreducibles)):
            g = irreducibles[j]
            if len(value) + len(g) - 2 <= limit:
                extend(independent_mul(value, g, p), j, chosen + [g])
    extend((1,), 0, [])
    assert len(expected) == sum(p ** d for d in range(1, limit + 1))
    for f, counts in expected.items():
        for unit in range(1, p):
            a = [unit * x % p for x in f]
            u, fs = factor(a, p)
            assert u == unit
            assert {tuple(g): e for g, e in fs} == dict(counts)
            assert verify(certificate(a, p), p, a)
            checked += 1
    for unit in range(1, p):
        assert factor([unit], p) == (unit, [])
print("exhaustive nonconstant cases:", checked)
with TemporaryDirectory() as directory:
    path = Path(directory) / "cert.sqlite3"
    f = [1, 0, 1, 0, 1]
    con = sqlite3.connect(path)
    con.execute("CREATE TABLE cert(id TEXT PRIMARY KEY, payload TEXT NOT NULL)")
    with con:
        save(con, "disk", certificate(f, 2))
    con.close()
    con = sqlite3.connect(path)
    print("disk replay:", replay(con, "disk", 2, f))
    con.close()

输出:

exhaustive nonconstant cases: 302
disk replay: True

复杂度、可信边界与下一步

对原始次数 n,枚举次数 d 的首一候选恰有 pᵈ 个。最坏情况下需要考察从一次到 ⌊n/2⌋ 次的候选,总数是这些幂的和;这里的朴素长除法每次最多使用 O(n²) 次域运算,因此可给出 O(n²Σpᵈ+n³) 的保守上界,其中额外成功试除至多 n 次。候选由生成器逐一产出,不必一次存满集合。这个界关于次数呈指数增长,也不是关于 log p 的多项式时间保证。八次、模七的上界已经有二千八百个不同首一候选,放开限制前应先更换算法,而不是悄悄删掉保护条件。

验证器为了证明每个因子不可约,也使用穷举小因子,故验证成本不保证显著低于求解成本;所谓证书在这里强调结构化记录与可复算,不暗示密码学意义的简洁证明。更大规模可使用平方自由分解、不同次数分解及相同次数分解的标准路线,或者成熟的 Berlekamp 实现。替换求解器时,可以继续保留可信输入绑定、单位与重数规范、乘回检查和磁盘回放这些工程约束。

真实系统还应明确可信输入的来源、数据库文件权限、模式版本、事务失败处理和备份策略。SQLite 的事务原子性只能保证数据库修改成组生效,不能自动保证记录所描述的数学结论为真。本例也没有提供签名、跨机器身份认证或并发队列。把这些边界说清楚,才能让一个简短实验成为可审查的基础,而不是看起来正确的黑箱。

资料与核对依据

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。