模数不互素也能合并:用 Python 与 SQLite 实现可审计的广义中国剩余定理
两条周期规则分别要求“每六个刻度余二”和“每九个刻度余八”,它们能否同时成立?答案是能:八、二十六、四十四都满足条件。六与九并不互素,所以把模数直接相乘、再套用互素版本的中国剩余定理,会把正确周期十八误写成五十四。实际工程更需要回答三个问题:有没有解,怎样用一个规范结果表示全部解,以及失败时能否给出别人可以复核的理由。
本文从这个小问题出发,用 Python 标准库完成广义中国剩余定理,再用 SQLite 保存原始输入、增量状态和审计证书。场景可以是整数刻度上的周期对齐、固定分桶条件交集或离散序号约束。这里所有余数都必须精确,不处理测量噪声;把真实日历换算为刻度时,时区、夏令时与变长月份需要在进入算法前另行建模。

运行环境为 Python 3.12 或更新版本,仅使用标准库;本文实际验证环境为 Python 3.12.14、SQLite 3.53.1。下面九个 Python 示例均可单独复制运行,不依赖前面的变量或文件。数据库示例默认使用内存库,不会改动现有数据库。重复出现的短函数是为了保持每段示例独立,工程项目中应提取成统一模块。
一、先规定输入契约与规范表示
用数对(a,m)表示 x 与 a 对模 m 同余。本文只接受正模数,结果统一为零到 m−1 之间的最小非负余数。负余数完全合法:−4 对模六与二等价;模数一也合法,它表示所有整数,不提供额外限制。相反,模数零没有本文使用的同余语义,应当直接拒绝,不能悄悄改成一。负模数也选择拒绝,而不是在接口里隐式取绝对值。
类型验证同样属于算法契约。Python 中布尔值是整数的子类,因此简单的 isinstance 检查会把 True 当作一。这个接口使用精确类型检查,拒绝布尔值、浮点数和字符串,避免把输入错误伪装成数学条件。外部 JSON 或表单的十进制文本应在边界层解析,并保留原始文本用于业务追踪,不能经由浮点数中转。
def normalize(a, m):
if type(a) is not int or type(m) is not int:
raise TypeError("a and m must be integers, not bool")
if m <= 0:
raise ValueError("modulus must be positive")
return a % m, m
for pair in [(-4, 6), (14, 6), (999, 1)]:
print(pair, "->", normalize(*pair))
for pair in [(2, 0), (True, 6), (2.0, 6)]:
try:
normalize(*pair)
except (TypeError, ValueError) as exc:
print(pair, "->", type(exc).__name__)运行输出:
(-4, 6) -> (2, 6) (14, 6) -> (2, 6) (999, 1) -> (0, 1) (2, 0) -> ValueError (True, 6) -> TypeError (2.0, 6) -> TypeError
这一步把“等价条件”变成唯一的表示,后续比较状态、检查幂等记录和复核证书才不会被不同写法干扰。保留原始输入与规范值是两件事,不能为了规范化而抹掉审计需要的来源信息。
二、兼容性证书:最大公约数必须整除余数差
设两条约束为 x≡a(mod m)与 x≡b(mod n),并令 g=gcd(m,n)。如果存在共同解,那么 x−a 与 x−b 分别被 m、n 整除,也都被 g 整除;两式相减后,b−a 必须被 g 整除。这给出一个非常便宜的失败检查:余数差对 g 的余数不为零,就不可能有共同解。
对于二模六、八模九,g 为三,余数差六能被三整除;将八改为七后,余数差变成五,检查立即失败。证书不必只是一个模糊的错误字符串,可以保存规范化输入、g、余数差及其余数。复核者重新计算最大公约数和整除关系,就能确认这次拒绝是否有数学依据。证书需要绑定具体输入,单独一个“无解”标记无法解释冲突来自何处。
from math import gcd
def compatibility(a, m, b, n):
if any(type(v) is not int for v in (a, m, b, n)):
raise TypeError("integer inputs required")
if m <= 0 or n <= 0:
raise ValueError("positive moduli required")
a, b = a % m, b % n
g, delta = gcd(m, n), b - a
return {"a": a, "m": m, "b": b, "n": n,
"g": g, "delta": delta, "remainder": delta % g}
for pair in [(2, 6, 8, 9), (2, 6, 7, 9)]:
c = compatibility(*pair)
print(c)
print("compatible:", c["remainder"] == 0)运行输出:
{'a': 2, 'm': 6, 'b': 8, 'n': 9, 'g': 3, 'delta': 6, 'remainder': 0}
compatible: True
{'a': 2, 'm': 6, 'b': 7, 'n': 9, 'g': 3, 'delta': 5, 'remainder': 2}
compatible: False这里的 g 是重新计算得到的,并非可信输入。若从数据库或文件读取证书,复核者必须验证 g 确实是两个模数的最大公约数,不能仅相信证书宣称的整除关系。
三、从相容条件构造规范合并结果
必要条件也足够。把第一条约束写成 x=a+mk,代入第二条,得到 mk≡b−a(mod n)。当 g 整除余数差时,把 m、n 与余数差同时除以 g,新的两个模数因子 m/g 与 n/g 互素,因此可以求模逆元,得到 k 的一个规范值。令 q=n/g,则 k 等于(b−a)/g 乘以 m/g 在模 q 下的逆元,最后对 q 取余。
合并周期是 L=m×q,也就是最小公倍数;规范余数是 r=(a+mk) 对 L 取余。任意两个共同解之差同时被 m 和 n 整除,所以必被 L 整除;反过来,在 r 上增加任意整数倍 L,两个原约束仍然成立。这同时证明了结果存在、完整以及在规范区间内唯一。输出数对(r,L)代表全部整数解 r+tL,其中 t 可以为负。
Python 的三参数 pow 支持用负一次方求模逆,但要求底数与模数互素;我们在约分后调用它。q 等于一时,新约束已被旧周期包含,直接选 k=0,避免把退化情形藏在库行为里。失败证书的结果字段保持为空,调用者必须先检查 ok。关于逆元接口,见 Python 官方 pow 文档。
from math import gcd
def normalize(a, m):
if type(a) is not int or type(m) is not int:
raise TypeError("a and m must be integers, not bool")
if m <= 0:
raise ValueError("modulus must be positive")
return a % m, m
def merge(a, m, b, n):
a, m = normalize(a, m)
b, n = normalize(b, n)
g = gcd(m, n)
delta = b - a
c = {"a": str(a), "m": str(m), "b": str(b), "n": str(n),
"g": str(g), "delta": str(delta),
"remainder": str(delta % g), "ok": delta % g == 0,
"k": None, "r": None, "period": None}
if not c["ok"]:
return c
q = n // g
k = 0 if q == 1 else (delta // g * pow(m // g, -1, q)) % q
period = m * q
r = (a + m * k) % period
c.update(k=str(k), r=str(r), period=str(period))
return c
for args in [(2, 6, 8, 9), (8, 18, 2, 6), (2, 6, 7, 9)]:
c = merge(*args)
print("input:", args)
print("ok:", c["ok"], "g:", c["g"], "delta:", c["delta"])
print("solution:", c["r"], "period:", c["period"])运行输出:
input: (2, 6, 8, 9) ok: True g: 3 delta: 6 solution: 8 period: 18 input: (8, 18, 2, 6) ok: True g: 6 delta: -6 solution: 8 period: 18 input: (2, 6, 7, 9) ok: False g: 3 delta: 5 solution: None period: None
第二组展示整除关系:当前已经是八模十八,再加入二模六,不会把周期扩大到一百零八。把新周期写成两个模数的乘积虽然有时仍能生成一部分解,却会漏掉其他合法解,属于完整性错误。
四、多条约束逐条折叠,空输入也有意义
多条约束无需先枚举所有两两组合,也无需分解质因数。从(0,1)开始,把当前合并结果与下一条约束合并即可。这个初始状态表示全体整数,是交集操作的自然起点。每成功一步,新状态就精确表示到目前为止所有约束的交集;遇到失败,整个输入前缀已经无解,后续增加约束不可能恢复可行性。
下面继续加入五模七,得到(26,126)。交换相容约束的顺序,最终规范结果相同,因为交集相同;但中间状态、计算成本和首先报出的冲突位置可能不同。失败证书中的左侧是整个已接受前缀的摘要,不一定是某一条原始约束。若业务必须指出具体哪两个来源矛盾,可以在失败后额外扫描历史记录,检查每个旧约束与新约束的相容性,并保存来源标识。
这里采用“一处失败,整批无解”的函数语义,返回 None 与失败位置。不要把失败前的状态当作整个批次的答案。后面的在线接入示例会采用另一种明确的产品语义:保留历史可行状态,只拒绝本次新条件,两者不能混用。
from math import gcd
def normalize(a, m):
if type(a) is not int or type(m) is not int:
raise TypeError("a and m must be integers, not bool")
if m <= 0:
raise ValueError("modulus must be positive")
return a % m, m
def merge(a, m, b, n):
a, m = normalize(a, m)
b, n = normalize(b, n)
g = gcd(m, n)
delta = b - a
c = {"a": str(a), "m": str(m), "b": str(b), "n": str(n),
"g": str(g), "delta": str(delta),
"remainder": str(delta % g), "ok": delta % g == 0,
"k": None, "r": None, "period": None}
if not c["ok"]:
return c
q = n // g
k = 0 if q == 1 else (delta // g * pow(m // g, -1, q)) % q
period = m * q
r = (a + m * k) % period
c.update(k=str(k), r=str(r), period=str(period))
return c
def solve(rows):
r, period = 0, 1
for index, (a, m) in enumerate(rows, 1):
c = merge(r, period, a, m)
if not c["ok"]:
return None, {"index": index, "certificate": c}
r, period = int(c["r"]), int(c["period"])
return (r, period), None
rows = [(2, 6), (8, 9), (5, 7)]
print("empty:", solve([]))
print("forward:", solve(rows))
print("reverse:", solve(list(reversed(rows))))
result, failure = solve(rows + [(1, 2)])
print("failed index:", failure["index"])
print("failure remainder:", failure["certificate"]["remainder"])运行输出:
empty: ((0, 1), None) forward: ((26, 126), None) reverse: ((26, 126), None) failed index: 4 failure remainder: 1
例子的第四条要求奇数,而前三条的共同解必为偶数,所以失败余数为一。返回的失败位置从一开始计数,与人阅读输入列表的顺序保持一致。
五、让 SQLite 保存精确文本,让 Python 完成整数计算
Python 整数可随需要增长,而 SQLite 的 INTEGER 存储类最多使用八字节有符号整数。多个普通模数合并后,最小公倍数很容易超过这个范围。为了避免溢出、自动转换或浮点精度损失,本文把余数与模数写成规范十进制字符串,列声明为 TEXT,并且绑定的参数本身也是字符串。读取时再由 Python 转回整数,所有数学运算继续留在 Python。
示例同时保存原始余数和规范余数:前者便于解释调用者究竟提交了什么,后者便于复算。使用参数占位符传值,避免将输入拼接进 SQL。数据库的类型亲和性并不等同于强类型验证,实际服务仍需要在写入边界检查;如果有其他程序直接改表,读取时也必须重新验证。SQLite 的存储类与转换规则可查阅 官方数据类型说明。
还有一个容易漏掉的问题:文本列的排序是文本排序,不能用 ORDER BY modulus 获得数值大小顺序;也不要为了排序把大整数 CAST 成 INTEGER。本文按独立的递增序号回放记录,大整数列只承担精确存储。需要大规模数值检索时,应另外设计受约束的索引表示,而不是破坏原始精度。
import sqlite3
def normalize(a, m):
if type(a) is not int or type(m) is not int:
raise TypeError("integer inputs required")
if m <= 0:
raise ValueError("positive modulus required")
return a % m, m
con = sqlite3.connect(":memory:")
con.execute("""CREATE TABLE congruence (
id INTEGER PRIMARY KEY,
raw_a TEXT NOT NULL, modulus TEXT NOT NULL,
residue TEXT NOT NULL
)""")
raw_a, m = -(10 ** 40) + 17, 10 ** 40 + 7
r, m = normalize(raw_a, m)
con.execute("INSERT INTO congruence VALUES (?, ?, ?, ?)",
(1, str(raw_a), str(m), str(r)))
con.commit()
row = con.execute("SELECT raw_a, modulus, residue, typeof(modulus) "
"FROM congruence WHERE id = ?", (1,)).fetchone()
print("storage class:", row[3])
print("raw round trip:", int(row[0]) == raw_a)
print("modulus round trip:", int(row[1]) == m)
print("normalized residue:", int(row[2]))
con.close()运行输出:
storage class: text raw round trip: True modulus round trip: True normalized residue: 24
示例数字远超六十四位,读取后的模数与原值仍严格相等。Python 的大整数不是无限资源:某些版本对十进制文本转换设有长度限制。对来自外部的超长字符串应先检查长度,再尝试转换;不应为了接受不受控请求而全局关闭保护。详见 整数与字符串转换限制。
六、增量接入:状态与证书必须在同一事务内提交
现在做一个最小在线接入器。head 表保存已接受约束的交集,audit 表保存每次合法输入的数学判断,包括不相容请求。新的请求先获得写事务,再读取当前状态、计算证书、写审计行,成功时才更新 head。这样不会出现证书已写入而状态没更新,或两个写入者基于同一旧状态互相覆盖的半成品。
本例显式设置 autocommit=True,再通过 SQL 的 BEGIN IMMEDIATE、COMMIT 与 ROLLBACK 管理事务。这是 Python 3.12 起提供的连接参数,因此没有把版本下限写成三参数 pow 最早可用的版本。IMMEDIATE 会立即尝试启动写事务,竞争写入者可能遇到忙错误;timeout 只是等待上限,不能保证一定成功。连接事务行为见 Python sqlite3 文档,写锁时机见 SQLite 事务文档。
请求标识还承担幂等键作用。同一个标识与完全相同的原始整数输入重试,会读取已有结果,不新增审计行;同一标识绑定不同输入则报错。这里比较的是原始整数,不是数学等价类,所以二与十四对模六虽等价,仍不能冒用同一请求标识。实际接口需要让调用者在网络重试时复用这个标识,并对忙错误做有界重试。
from math import gcd
def normalize(a, m):
if type(a) is not int or type(m) is not int:
raise TypeError("a and m must be integers, not bool")
if m <= 0:
raise ValueError("modulus must be positive")
return a % m, m
def merge(a, m, b, n):
a, m = normalize(a, m)
b, n = normalize(b, n)
g = gcd(m, n)
delta = b - a
c = {"a": str(a), "m": str(m), "b": str(b), "n": str(n),
"g": str(g), "delta": str(delta),
"remainder": str(delta % g), "ok": delta % g == 0,
"k": None, "r": None, "period": None}
if not c["ok"]:
return c
q = n // g
k = 0 if q == 1 else (delta // g * pow(m // g, -1, q)) % q
period = m * q
r = (a + m * k) % period
c.update(k=str(k), r=str(r), period=str(period))
return c
import json
import sqlite3
def open_db(path=":memory:"):
# Python 3.12+: explicit SQL transactions, no implicit BEGIN.
con = sqlite3.connect(path, autocommit=True, timeout=5.0)
con.executescript("""
CREATE TABLE IF NOT EXISTS head (
id INTEGER PRIMARY KEY CHECK(id = 1),
r TEXT NOT NULL, period TEXT NOT NULL
);
INSERT OR IGNORE INTO head VALUES (1, '0', '1');
CREATE TABLE IF NOT EXISTS audit (
seq INTEGER PRIMARY KEY,
request_id TEXT NOT NULL UNIQUE,
raw_a TEXT NOT NULL, raw_m TEXT NOT NULL,
certificate TEXT NOT NULL
);
""")
return con
def append(con, request_id, a, m):
normalize(a, m) # Invalid input is rejected before the audit transaction.
if type(request_id) is not str or not request_id:
raise ValueError("nonempty request_id required")
con.execute("BEGIN IMMEDIATE")
try:
previous = con.execute(
"SELECT raw_a, raw_m, certificate FROM audit WHERE request_id = ?",
(request_id,)).fetchone()
if previous:
if previous[:2] != (str(a), str(m)):
raise ValueError("request_id reused with different input")
con.execute("COMMIT")
return json.loads(previous[2]), True
r, period = map(int, con.execute(
"SELECT r, period FROM head WHERE id = 1").fetchone())
c = merge(r, period, a, m)
con.execute("INSERT INTO audit(request_id, raw_a, raw_m, certificate) "
"VALUES (?, ?, ?, ?)",
(request_id, str(a), str(m),
json.dumps(c, sort_keys=True, separators=(",", ":"))))
if c["ok"]:
con.execute("UPDATE head SET r = ?, period = ? WHERE id = 1",
(c["r"], c["period"]))
con.execute("COMMIT")
return c, False
except BaseException:
if con.in_transaction:
con.execute("ROLLBACK")
raise
if __name__ == "__main__":
con = open_db()
for key, a, m in [("A", 2, 6), ("B", 8, 9), ("C", 7, 9), ("B", 8, 9)]:
c, cached = append(con, key, a, m)
print(key, "accepted:", c["ok"], "cached:", cached)
print("head:", con.execute("SELECT r, period FROM head").fetchone())
print("audit rows:", con.execute("SELECT COUNT(*) FROM audit").fetchone()[0])
con.close()运行输出:
A accepted: True cached: False
B accepted: True cached: False
C accepted: False cached: False
B accepted: True cached: True
head: ('8', '18')
audit rows: 3第三条 C 无法与已接受的 A、B 共存,因此它的失败证书被提交,但 head 保持八模十八。这表示“本次接入被拒绝”,不表示 A、B、C 组成的整个集合有解。类型错误、非法模数、键冲突和数据库异常与数学冲突分别处理;本例不为前几类错误创建数学证书,事务异常会回滚。生产环境可以另设操作日志记录这些接口失败。
把内存地址换成文件路径即可保留数据库,但持久化部署还应明确权限、备份、恢复与迁移方案。本文不关闭同步或事务保护来追求漂亮的测速数字。删除或改写历史约束会改变交集,不能从当前摘要简单做减法;通常需要从剩余被接受记录重新构建,或使用带版本的检查点。
七、独立回放证书,不重新调用同一个求解器
“再运行一遍合并函数”只能说明同一个实现前后表现一致,无法有效发现它自身的逻辑缺陷。更好的审核路径是直接验证数学后置条件:失败时重新检查最大公约数与非零余数;成功时检查结果规范区间、两个原始同余式、最小公倍数,以及见证值 k。下面的校验器不调用 merge,也不使用模逆元来重新求解。
回放不仅校验单行,还验证序号、请求标识唯一性、原始输入与证书右侧的绑定,以及证书左侧是否接在前一成功状态之后。失败记录不得推进状态。实际读取 audit 时按 seq 排序,对 certificate 字段做 JSON 解析,组成下面的元组列表即可;最后还要把回放状态与 head 表比较,不能只看每行证书是否自洽。在线审计时,应在同一个显式只读事务的快照中读取 audit 与 head,避免两次查询之间的新提交造成误报。
为让示例独立运行,这里内嵌三行小型快照,数值与前一节一致。若还允许从外部文件导入记录,需额外严格检查 seq 为整数、请求标识为非空字符串;本文示例的行结构来自受控数据库。校验器要求十进制表示规范,拒绝多余前导零或空白,并对文本长度设定一千字符的演示上限。真实服务要为输入、合并结果和回放器配置一致的位数预算;不能让写入端无限接受数据,却让审核端无法读取。
from math import gcd
def require(condition, message):
if not condition:
raise ValueError(message)
def integer_text(value):
require(type(value) is str and 0 < len(value) <= 1000,
"integer text length/type")
try:
number = int(value)
except ValueError as exc:
raise ValueError("invalid integer text") from exc
require(str(number) == value, "noncanonical integer text")
return number
def verify(c):
names = "a m b n g delta remainder".split()
require(set(c) == set(names + ["ok", "k", "r", "period"]), "fields")
a, m, b, n, g, delta, rem = [integer_text(c[key]) for key in names]
require(m > 0 and n > 0 and 0 <= a < m and 0 <= b < n, "domain")
require(g == gcd(m, n) and delta == b - a and rem == delta % g,
"compatibility certificate")
require(type(c["ok"]) is bool and c["ok"] == (rem == 0), "status")
if rem:
require(all(c[key] is None for key in ("k", "r", "period")),
"failed result must be absent")
return None
k, r, period = [integer_text(c[key]) for key in ("k", "r", "period")]
require(period == m // g * n and 0 <= r < period, "normal form")
require(r % m == a and r % n == b, "residue mismatch")
require(0 <= k < n // g and (a + m * k) % period == r, "witness k")
return r, period
def replay(rows):
state, seen = (0, 1), set()
for expected_seq, (seq, key, raw_a, raw_m, c) in enumerate(rows, 1):
require(seq == expected_seq and key not in seen, "sequence or key")
seen.add(key)
raw_a, raw_m = integer_text(raw_a), integer_text(raw_m)
require(raw_m > 0, "input modulus")
result = verify(c)
require((int(c["a"]), int(c["m"])) == state, "broken state chain")
require((int(c["b"]), int(c["n"])) == (raw_a % raw_m, raw_m),
"input binding")
if result is not None:
state = result
return state
from copy import deepcopy
# A self-contained snapshot in the same shape as SELECT ... ORDER BY seq.
rows = [
(1, "A", "2", "6", dict(a="0", m="1", b="2", n="6", g="1",
delta="2", remainder="0", ok=True, k="2", r="2", period="6")),
(2, "B", "8", "9", dict(a="2", m="6", b="8", n="9", g="3",
delta="6", remainder="0", ok=True, k="1", r="8", period="18")),
(3, "C", "7", "9", dict(a="8", m="18", b="7", n="9", g="9",
delta="-1", remainder="8", ok=False, k=None, r=None, period=None)),
]
print("replayed head:", replay(rows))
bad = deepcopy(rows)
bad[1][4]["r"] = "9"
try:
replay(bad)
except ValueError as exc:
print("modified result detected:", exc)运行输出:
replayed head: (8, 18) modified result detected: residue mismatch
这些记录提供的是可复算性,并不是防篡改认证。能同时重写输入、证书与状态的人,仍可能造出另一条数学上自洽的历史;单纯重放也无法发现末尾记录被整体删去。若需要证明记录完整或来源真实,应另外建立可信序号边界、权限隔离、外部存证或签名,并明确密钥与信任边界。不要把普通 SQLite 表称为不可篡改账本。
八、把无限解集转换为指定窗口内的答案
得到(r,L)后,很多应用真正需要的是闭区间下界到上界之间的第一次命中与总次数。直接枚举所有整数太慢,用浮点除法再向上取整则可能在大整数边界上出错。令 k 为(lower−r)/L 的向上取整,则第一个候选就是 r+kL;它超过上界时,窗口内无解,否则数量可用一次整除算出。
Python 的整除向下取整,因此可以用整数恒等式改写向上取整,全程没有浮点数。下界为负也能正确工作,不要额外把 k 限制为非负:规范余数非负,并不意味着全部解都非负。若业务只允许未来时间或非负序号,应把这个限制体现为窗口下界,而不是更改 CRT 的数学定义。
def in_window(r, period, lower, upper):
if any(type(v) is not int for v in (r, period, lower, upper)):
raise TypeError("integer inputs required")
if period <= 0 or not 0 <= r < period:
raise ValueError("normalized solution required")
if lower > upper:
return None, 0
k = -((r - lower) // period) # ceil((lower - r) / period)
first = r + k * period
if first > upper:
return None, 0
return first, (upper - first) // period + 1
for bounds in [(0, 50), (9, 20), (-40, 10), (10, 9)]:
print(bounds, "->", in_window(8, 18, *bounds))运行输出:
(0, 50) -> (8, 3) (9, 20) -> (None, 0) (-40, 10) -> (-28, 3) (10, 9) -> (None, 0)
例如窗口零到五十内的解是八、二十六、四十四,合计三次;窗口九到二十没有解;窗口负四十到十则包含负二十八、负十和八。返回首次命中与数量通常已经足够,如果还要列出全部结果,应先限制数量,避免把一个巨大的区间一次性装入内存。
九、用穷举判定器检查小规模全部输入
只展示几个成功样例,远不足以覆盖不互素、重复模数、整除关系和负余数。最后建立一个独立的小规模判定器:先算各模数的最小公倍数,再在一个完整周期内逐个检查整数。它故意不使用合并公式,因此适合给快速算法做交叉验证。测试范围有限,穷举很慢也没关系;它的任务是提供容易理解的正确性参照。
下面覆盖模数一到八、余数负八到八的全部二元组合,共一万八千四百九十六组;再覆盖模数一到四的所有规范同余式组成的三元组,共一千组。额外检查空输入与三条相容约束的所有排列。断言验证的是“无解或规范结果完全一致”,不仅是某个返回数字碰巧满足条件。错误地返回过大的周期,也会被这个测试发现。
穷举测试不替代前面的数学证明,也不能证明数据库崩溃恢复或并发处理没有缺陷。随文测试还检查了大整数往返、幂等重试、请求键冲突、事务回滚、审计篡改检测与双连接写锁。性能测试应另外计量:合并次数随输入条数增加,但每一步的大整数长度也可能增长,不能把整个过程简单宣传成与数字大小无关的线性时间。
from math import gcd
def normalize(a, m):
if type(a) is not int or type(m) is not int:
raise TypeError("a and m must be integers, not bool")
if m <= 0:
raise ValueError("modulus must be positive")
return a % m, m
def merge(a, m, b, n):
a, m = normalize(a, m)
b, n = normalize(b, n)
g = gcd(m, n)
delta = b - a
c = {"a": str(a), "m": str(m), "b": str(b), "n": str(n),
"g": str(g), "delta": str(delta),
"remainder": str(delta % g), "ok": delta % g == 0,
"k": None, "r": None, "period": None}
if not c["ok"]:
return c
q = n // g
k = 0 if q == 1 else (delta // g * pow(m // g, -1, q)) % q
period = m * q
r = (a + m * k) % period
c.update(k=str(k), r=str(r), period=str(period))
return c
def solve(rows):
r, period = 0, 1
for index, (a, m) in enumerate(rows, 1):
c = merge(r, period, a, m)
if not c["ok"]:
return None, {"index": index, "certificate": c}
r, period = int(c["r"]), int(c["period"])
return (r, period), None
from itertools import product, permutations
from math import lcm
def oracle(rows):
period = lcm(*(m for _, m in rows))
values = [x for x in range(period)
if all(x % m == a % m for a, m in rows)]
return None if not values else (values[0], period)
pairs = 0
for m, n in product(range(1, 9), repeat=2):
for a, b in product(range(-8, 9), repeat=2):
rows = [(a, m), (b, n)]
result, _ = solve(rows)
assert result == oracle(rows), rows
pairs += 1
choices = [(a, m) for m in range(1, 5) for a in range(m)]
triples = 0
for rows in product(choices, repeat=3):
result, _ = solve(rows)
assert result == oracle(rows), rows
triples += 1
rows = [(2, 6), (8, 9), (5, 7)]
assert all(solve(order)[0] == (26, 126) for order in permutations(rows))
assert solve([])[0] == (0, 1)
print("pair cases:", pairs)
print("triple cases:", triples)
print("oracle, permutations and empty input: PASS")运行输出:
pair cases: 18496 triple cases: 1000 oracle, permutations and empty input: PASS
所有输出均由对应示例实际运行生成。测试中的 assert 仅用于开发验证,运行时不要加会移除断言的优化参数;面向外部输入的生产校验应像第七节一样使用显式异常。扩展测试可以随机生成一个隐藏整数,再从它产生一组必相容余数,并随机扰动某条约束,检查失败与恢复的语义。
收束:把算术事实、产品语义与存储责任分开
这套实现最重要的不是一行逆元公式,而是明确边界:正模数与规范余数定义接口,最大公约数给出相容判定,最小公倍数保证完整周期,失败证书解释无解,事务保证状态与记录一致,独立回放检查结论。把这些责任拆开后,算法才能从练习题变成可检查、可维护的组件。
读者可以继续为约束增加来源标识、批次号和版本,并把业务层的接入策略写成测试:到底是整批接受、整批失败,还是逐条拒绝不相容输入?先确定这件事,再设计接口状态码。数学上的交集没有歧义,服务端是否保留旧状态则是必须明确记录的产品选择。
参考资料与验证范围
Python math.gcd 与 math.lcm 官方说明:对应最大公约数及测试中的最小公倍数。
Python pow 官方说明:对应约分后求模逆的调用条件。
Python sqlite3 官方说明与SQLite 事务说明:对应参数绑定和显式事务。
SQLite 数据类型说明:对应整数范围、文本存储和类型亲和性。
SymPy solve_congruence 官方文档:作为不互素模数求解接口的参考对照;本文实现与测试不依赖 SymPy。
资料核验日期:2026 年 10 月 19 日。公式推导、示例代码、数据库接入策略和小规模穷举判定器均为本文独立组织;没有使用浮点近似,也没有宣称测试覆盖了任意规模或所有部署故障。

