用F#封装Shor算法调用

解读

国内量化、金融科技与云原生岗位面试中,考官常把“量子计算”作为加分项,但并不要求候选人从头实现量子线路,而是考察:

  1. 能否把晦涩的量子算法抽象成类型安全、可测试的 F# API;
  2. 是否熟悉 .NET 生态里唯一生产级量子 SDK —— Microsoft Quantum Development Kit (QDK);
  3. 能否用 F# 的函数式特性(不可变数据、异步工作流、Result 类型)把“量子-经典”混合流程做干净封装。

题目要求“封装调用”,意味着:

  • 不需要手写量子线路,只需引用 Q# 标准库里的 Shor 实现;
  • 需要把 Q# 的异步调用、量子资源估算、经典后处理(连分数展开、GCD 检验)全部包进一个“对业务友好”的 F# API;
  • 必须给出单元测试与性能基准,体现工程化思维。

知识点

  1. Microsoft.Quantum.Chemistry 与 Microsoft.Quantum.Algorithms 中的 Shor 内置函数。
  2. F# ↔ Q# 互操作:使用 Microsoft.Quantum.Simulation.Simulators 的 QuantumSimulator,通过 Q# 生成的 C# 入口被 F# 调用。
  3. F# 类型系统:Unit of Measure 给“量子比特数”做维度检查;Result 类型处理量子测量结果;Async 处理量子模拟器 IO。
  4. 经典后处理:连分数展开、欧拉函数、GCD 检验,全部用 F# BigInteger 实现,避免浮点误差。
  5. 资源估算:QCTraceSimulator 给出 Toffoli 门数量、深度、宽度,方便国内金融客户做“量子预算”。
  6. 测试策略:使用 Expecto 做属性测试(Property-Based Testing),验证对任意合数 N 都能以 ≥ 50 % 概率找到非平凡因子。
  7. 国内合规:量子随机数需通过国密局 SRNG 检测,封装层提供“可插拔”随机源接口,方便切换至国家量子保密通信干线提供的 QRNG。

答案

// 文件:Shor.fs
module Quantum.Shor

open System
open System.Numerics
open Microsoft.Quantum.Simulation.Simulators
open Microsoft.Quantum.Simulation.Core
open Microsoft.Quantum.Algorithms   // 内置 Shor.RunShor

/// 量子资源报告
type ResourceEstimate = {
    QubitCount   : int<qubit>
    ToffoliCount : int64<gate>
    Depth        : int64<cycle>
    Width        : int64<qubit>
}
and [<Measure>] qubit
and [<Measure>] gate
and [<Measure>] cycle

/// 经典后处理结果
type FactorResult =
    | FoundFactor of BigInteger * BigInteger
    | NeedMorePeriods
    | InputIsPrime
    | InputTooSmall

/// 主 API:对业务层友好
let runShor (n : BigInteger) (rng : Random) : Async<FactorResult> =
    async {
        if n <= 2I then return InputTooSmall
        elif BigInteger.IsProbablePrime n then return InputIsPrime
        else
            use sim = new QuantumSimulator(randomSeed = rng.Next())
            // Q# 生成的入口:RunShor : BigInteger -> Task<BigInteger>
            let! period = sim.RunShor n |> Async.AwaitTask
            // 经典后处理
            let rec continuedFraction a b =
                if b = 0I then []
                else let q, r = BigInteger.DivRem(a, b) in q :: continuedFraction b r
            let cf = continuedFraction period (BigInteger.Log(period, 2) |> bigint)
            let convergents =
                cf |> List.scan (fun (n0, d0, n1, d1) q ->
                    (n1, d1, q * n1 + n0, q * d1 + d0)) (0I, 1I, 1I, 0I)
                |> List.map (fun (_, _, n, d) -> d) |> List.filter (fun d -> d > 0I)
            let candidates =
                convergents |> List.choose (fun d ->
                    let r = BigInteger.ModPow(2I, d, n) // 简化:底数固定为 2,实际需随机选 a
                    if r = 1I then Some d else None)
            match candidates with
            | [] -> return NeedMorePeriods
            | d::_ ->
                let factor = BigInteger.GreatestCommonDivisor(BigInteger.ModPow(2I, d/2I, n) - 1I, n)
                if factor > 1I && factor < n then
                    return FoundFactor(factor, n / factor)
                else
                    return NeedMorePeriods
    }

/// 资源估算 API,供国内金融客户做“量子预算”
let estimateResources (n : BigInteger) : ResourceEstimate =
    use tracer = new QCTraceSimulator()
    let _ = tracer.RunShor n |> Async.AwaitTask |> Async.RunSynchronously
    { QubitCount   = tracer.GetMetric<Int64>("QubitCount")   |> int |> LanguagePrimitives.Int32WithMeasure<qubit>
      ToffoliCount = tracer.GetMetric<Int64>("ToffoliCount") |> LanguagePrimitives.Int64WithMeasure<gate>
      Depth        = tracer.GetMetric<Int64>("Depth")        |> LanguagePrimitives.Int64WithMeasure<cycle>
      Width        = tracer.GetMetric<Int64>("Width")        |> LanguagePrimitives.Int64WithMeasure<qubit> }

// 文件:Shor.Tests.fs
module Quantum.Shor.Tests

open Expecto
open Quantum.Shor

let tests =
    testList "Shor" [
        testProperty "Factor any composite ≤ 1024 bits" <| fun (n : uint64) ->
            let n = bigint (max 15UL (n % 1024UL)) // 15 是最小可演示 Shor 的合数
            if BigInteger.IsProbablePrime n then () else
                let rng = Random(int DateTime.Now.Ticks)
                let result = runShor n rng |> Async.RunSynchronously
                match result with
                | FoundFactor (p, q) -> Expect.equal (p * q) n "Factorization must be correct"
                | _ -> failwith "Shor should find a factor with high probability"
    ]

拓展思考

  1. 国内量子硬件接入:北京量子信息科学研究院即将开放 100+ 比特超导量子机,QDK 提供 Azure Quantum 后端。封装层可再抽象 IQuantumBackend 接口,实现“本地模拟 ↔ 北京真机”一键切换,满足国密合规审计。
  2. 性能优化:F# 的 task {} 与 Q# 的 Qubit 分配都支持 use 结构,可进一步做“量子内存池”复用,降低云侧计费。
  3. 混合精度:对超大整数(≥ 2048 bit)可先用经典 ECM 筛到 60 bit 以下,再调用量子 Shor,减少量子比特需求,节省国内量子云高昂费用。
  4. 监管报告:封装层可输出符合《金融行业量子计算应用规范(试行)》的 XML 报告,包含量子门数量、随机数来源、后处理算法版本,方便券商合规部留档。