# Demo 1:Shor 破 RSA > 第 16 章 译码与量子密码分析 · [本章演示](index.md) · [代码演示总索引](../index.md) **可视化**:单子图 —— 3+3 qubit QPE 估 r=4 + GCD **对应教程**:[第 16 章 译码与量子密码分析 中相关小节](https://tutorial.chenzhaoyun.com/quantum-tutorial/ch16-cryptanalysis-coding/) · 依赖安装:`pip install "unified-quantum[visualization,simulation]"` ## 实现要点 核心:Shor 算法把整数分解归约为周期寻找。给定 N = 15,随机选 a = 7, f(x) = 7^x mod 15 以 r = 4 为周期。量子部分用相位估计 (QPE) 提取 s/r 的足够精确二进近似;经典后处理通过连分数展开恢复 r,再用 gcd(a^(r/2) ± 1, N) 得到非平凡因子。本 demo 用 uniqc 的 qpe_circuit helper 构造周期 4 的酉算子 U(在 |000⟩-|011⟩ 子空间上的本征值为 e^{2πi s/4}, s=0,1,2,3),跑 3-比特 QPE,测出 phase s/4,然后 连分数得到 r = 4,最后 gcd(7^2 ± 1, 15) = 3, 5 恢复因子。 ## 完整源码 ```{literalinclude} 01_shor_rsa.py :language: python :linenos: :caption: demos/ch16-cryptanalysis-coding/01_shor_rsa.py ``` ## 运行结果 ![Demo 1:Shor 破 RSA](01_shor_rsa.png) ## 运行方式 ```bash # 仓库根目录执行;输出 PNG 到 demos/ch16-cryptanalysis-coding/01_shor_rsa.png,关键统计到 stdout .venv/bin/python3 demos/ch16-cryptanalysis-coding/01_shor_rsa.py ``` --- [← 本章演示](index.md) · [↑ 代码演示总索引](../index.md) · [⌂ 教程门户](https://tutorial.chenzhaoyun.com/)