Compile and execute Shor’s algorithm¶
Factor 21 with a structured quantum program, the compiler, and the bundled DDSIM simulator. Install MQT Core as described in Installation. The Python wheel includes the compiler and simulator used here.
Factor a number¶
Shor’s algorithm combines quantum order finding with classical factor recovery. For a chosen base \(a\) coprime to \(N\), the quantum circuit estimates phases of the modular multiplication \(x \mapsto ax \bmod N\). Continued fractions yield candidate exponents from the measured phases. The driver checks each exponent by modular exponentiation, uses greatest common divisors to find possible factors, and verifies them by division.
The factoring driver selects bases and recovers factors. You provide a run
callback that executes each generated circuit and returns its counts. This lets
you choose the device, compilation settings, shot count, and random seed:
1from mqt.core.bench import shor
2from mqt.core.mlir import submit_program
3from mqt.core.qdmi import ProgramFormat, open_device
4
5device = open_device("mqt.ddsim.default")
6
7
8def run(benchmark: shor.Shor) -> dict[str, int]:
9 job = submit_program(benchmark.generate(), target=device, program_format=program_format, num_shots=64, custom1=17)
10 job.wait()
11 return job.get_counts()
12
13
14for program_format in (ProgramFormat.QIR_ADAPTIVE_MODULE, ProgramFormat.QASM3):
15 result = shor.factor(21, run)
16 assert result.status == shor.FactorStatus.SUCCESS
17 assert result.factors == (3, 7)
18 print(f"{program_format.name}: {result.factors}")
QIR_ADAPTIVE_MODULE: (3, 7)
QASM3: (3, 7)
submit_program() compiles the program for the
destination and creates a device job in one call. Use
compile_program() separately when reusing a native
CompiledProgram for multiple jobs. job.wait() waits
for completion and reports execution failure. Both Adaptive QIR and OpenQASM 3
execute the same circuit; custom1=17 selects DDSIM’s random seed. Custom job
properties are device-specific.
The driver first checks for even numbers, primes, and perfect powers. These need
no quantum execution and use zero attempts. Otherwise it tries base 2, then
seeded random bases, up to max_attempts=16. A base with a nontrivial common
divisor can reveal a factor before execution. A circuit whose counts yield no
factors causes another attempt. The result reports SUCCESS, PRIME, or
ATTEMPTS_EXHAUSTED, an optional sorted factor pair, and the number of
attempted bases. It returns one pair, not a recursive prime factorization.
Inspect one order-finding circuit¶
Use a single-base benchmark to inspect the quantum and classical steps. For \(N=21\) and \(a=2\), the circuit uses \(2n+3=13\) qubits, where \(n=\operatorname{bit\_width}(21)=5\). One query qubit is measured and reset for each of the \(2n=10\) phase bits. The value register persists across rounds; modular arithmetic restores its temporary qubits after each multiplication. Earlier measurements control phase corrections on the query qubit. This combines a semiclassical QFT with qubit recycling; the benchmark reference describes the circuit.
1benchmark = shor.Shor(shor.Options(number=21, base=2))
2counts = run(benchmark)
3evaluation = benchmark.evaluate(counts)
4assert sum(counts.values()) == 64
5assert evaluation.factors == (3, 7)
6print(f"Verified factors: {evaluation.factors}")
7print(f"Successful shot fraction: {evaluation.success_probability:.3f}")
Verified factors: (3, 7)
Successful shot fraction: 0.344
Counts put the highest-index phase bit on the left, so each bitstring encodes an
integer \(y\) and an estimate \(y/2^{10}\). Equivalent OpenQASM and QIR programs use
the same bit order. The benchmark accepts job.get_counts() directly.
Select an observed outcome that yields factors and inspect its rational approximation:
1from fractions import Fraction
2from math import gcd
3
4outcome = next(
5 bits for bits in sorted(counts, key=lambda bits: counts[bits], reverse=True)
6 if benchmark.evaluate({bits: 1}).factors is not None
7)
8phase = Fraction(int(outcome, 2), 2**benchmark.output.width)
9approximation = phase.limit_denominator(benchmark.options.number - 1)
10r = approximation.denominator
11assert r % 2 == 0
12assert pow(benchmark.options.base, r, benchmark.options.number) == 1
13half_power = pow(benchmark.options.base, r // 2, benchmark.options.number)
14p = gcd(half_power - 1, benchmark.options.number)
15q = gcd(half_power + 1, benchmark.options.number)
16assert tuple(sorted((p, q))) == (3, 7)
17print(f"Measured {outcome}: {phase}, near {approximation}")
18print(f"Candidate exponent: {r}; gcd recovery: {p}, {q}")
Measured 1101010101: 853/1024, near 5/6
Candidate exponent: 6; gcd recovery: 7, 3
For example, \(171/1024\) is close to \(1/6\). The candidate exponent 6 satisfies \(2^6 \equiv 1 \pmod{21}\), and \(2^{6/2}=8\) gives \(\gcd(8-1,21)=7\) and \(\gcd(8+1,21)=3\).
This single approximation illustrates a successful sample. The native
evaluate() examines exact
continued-fraction convergents with denominators
below \(N\) and verifies each candidate. A reduced phase such as \(2/6=1/3\) need
not retain the order in its denominator. Zero phases, unsuitable exponents, and
trivial greatest common divisors are ordinary unsuccessful samples. More shots
and, when needed, new bases give further chances to recover factors.
success_probability is the observed fraction of shots that independently yield
a verified pair. It is not a distance from an ideal distribution. Shor provides
a verification reference and does not report total variation distance or
Hellinger fidelity.
Continue¶
Work through the compiler tutorial to explain representations, optimizations, control flow, and hardware constraints.
Use Compile for a QDMI device and Using QDMI drivers to compile for other devices and inspect their capabilities.
Explore Quantum benchmarks for other program families and reference metrics.