Lesson 42: Microsoft Q# and the Quantum Development Kit¶
42.1 Learning Outcomes¶
By the end of this hour a student will be able to:
- Write Q# programs using operations, functions and its type system.
- Explain Q#'s distinctive features: adjoint/controlled functors,
use/borrow, andwithin/apply. - Use the Azure Quantum Resource Estimator to compute fault-tolerant requirements.
- Compare Q# with Python-embedded SDKs and state when a dedicated language pays off.
- Interpret a resource-estimation report.
42.2 Why a Dedicated Language?¶
Qiskit, Cirq, PennyLane and Braket are Python libraries: a circuit is data you build at runtime. Q# is a standalone programming language designed for quantum computation, with quantum semantics in the type system.
| Aspect | Python SDK | Q# |
|---|---|---|
| Circuit | a runtime data structure | a program |
| Qubit management | you index into a register | scoped allocation (use) |
| Adjoint of a subroutine | you rebuild it manually | Adjoint Op(...) — compiler-generated |
| Controlled version | manual | Controlled Op(...) — compiler-generated |
| Type safety | runtime errors | compile-time errors |
| Resource estimation | limited | first-class |
The payoff: for large, structured algorithms (Shor, chemistry simulation, error correction), Q# catches errors at compile time and generates adjoint and controlled variants automatically — work that in Python is manual, error-prone and a major source of bugs.
42.3 Q# Basics¶
Setup¶
pip install qsharp azure-quantum
import qsharp
qsharp.init(project_root='.')
qsharp.eval("""
operation BellPair() : (Result, Result) {
use (q0, q1) = (Qubit(), Qubit());
H(q0);
CNOT(q0, q1);
return (MResetZ(q0), MResetZ(q1));
}
""")
print(qsharp.run("BellPair()", shots=100))
Operations versus functions¶
// OPERATION: may have quantum side effects
operation ApplyH(q : Qubit) : Unit is Adj + Ctl {
H(q);
}
// FUNCTION: pure, deterministic, no quantum operations allowed
function Square(x : Int) : Int {
return x * x;
}
The compiler enforces the distinction. A function cannot call an operation, which guarantees
that functions are referentially transparent and safely reorderable.
Qubit allocation¶
operation Example() : Result {
use q = Qubit(); // allocated in |0>
use register = Qubit[5]; // an array of 5 qubits
use (a, b) = (Qubit(), Qubit()); // a tuple
H(q);
return MResetZ(q); // measure AND reset to |0>
} // qubits released automatically here
Q# requires qubits to be returned in \(|0\rangle\). A runtime check enforces this. It sounds pedantic, but it catches the single most common bug in quantum programming: forgetting to uncompute an ancilla, which leaves it entangled with the data and silently destroys interference (L11 §5). Python SDKs will happily run such a circuit and give wrong answers with no warning.
borrow requests dirty ancillas — qubits in an unknown state that you must restore. Useful for
memory-efficient arithmetic circuits.
Functors — Q#'s signature feature¶
operation MyOp(q : Qubit) : Unit is Adj + Ctl {
H(q);
T(q);
X(q);
}
// The compiler GENERATES these automatically:
Adjoint MyOp(q); // X, T-dagger, H (reversed and inverted)
Controlled MyOp([ctrl], q); // controlled version
Controlled Adjoint MyOp([c1, c2], q);
Why this matters enormously. Consider Shor's algorithm: it needs controlled modular exponentiation and the inverse QFT. In Qiskit you write the modular-exponentiation circuit, then write its controlled version by hand (adding a control to every gate), then write the inverse QFT by hand. Each is hundreds of lines and each is a fresh opportunity for a bug.
In Q#, Controlled ModExp(...) and Adjoint QFT(...) are generated by the compiler and guaranteed
correct.
The within/apply pattern¶
within {
H(q); // "compute"
CNOT(q, r);
} apply {
Z(r); // "action"
}
// The compiler automatically applies Adjoint of the `within` block afterwards:
// H, CNOT, Z, CNOT-dagger, H-dagger
This is the conjugation pattern \(UVU^\dagger\), which appears constantly: phase-oracle
construction (L11), basis changes, and every uncomputation. Writing it as within/apply makes the
uncomputation impossible to forget.
42.4 A Complete Program: Grover's Algorithm¶
namespace GroverExample {
open Microsoft.Quantum.Arrays;
open Microsoft.Quantum.Convert;
open Microsoft.Quantum.Diagnostics;
open Microsoft.Quantum.Math;
open Microsoft.Quantum.Measurement;
/// Phase-flips the marked basis state.
operation MarkState(marked : Bool[], register : Qubit[]) : Unit is Adj + Ctl {
within {
for (bit, q) in Zipped(marked, register) {
if not bit { X(q); } // flip the 0s to 1s
}
} apply {
Controlled Z(Most(register), Tail(register));
}
}
/// Inversion about the mean.
operation Diffuser(register : Qubit[]) : Unit is Adj + Ctl {
within {
ApplyToEachA(H, register);
ApplyToEachA(X, register);
} apply {
Controlled Z(Most(register), Tail(register));
}
}
@EntryPoint()
operation RunGrover(n : Int, marked : Bool[]) : Result[] {
use register = Qubit[n];
ApplyToEach(H, register);
let iterations = Round(PI() / 4.0 * Sqrt(IntAsDouble(2 ^ n)));
Message($"Running {iterations} Grover iterations on {n} qubits");
for _ in 1 .. iterations {
MarkState(marked, register);
Diffuser(register);
}
return ForEach(MResetZ, register);
}
}
Note how compact the oracle and diffuser are. The within/apply blocks handle all the
uncomputation; there is no chance of forgetting to undo the \(X\) gates.
42.5 The Resource Estimator — Q#'s Killer Feature¶
No other framework does this as a first-class capability.
import qsharp
from qsharp.estimator import EstimatorParams, QubitParams, QECScheme
params = EstimatorParams()
params.error_budget = 0.001
params.qubit_params.name = QubitParams.MAJ_NS_E6 # hypothetical Majorana qubit
params.qec_scheme.name = QECScheme.FLOQUET_CODE
result = qsharp.estimate("RunShor(2048)", params=params)
print(result.summary)
A representative report.
Physical qubits : 22,282,400
Runtime : 8.4 hours
Logical qubits : 4,116
Logical depth : 1.2e10
T states required : 6.1e10
T factories : 18
Code distance : 27
Physical error rate : 1e-4
Logical error rate : 3.2e-15
Reading a resource-estimation report.
| Field | Meaning | Why it matters |
|---|---|---|
| Physical qubits | total hardware required | the headline feasibility number |
| Logical qubits | error-corrected qubits used | algorithm-level requirement |
| Code distance \(d\) | error-correction strength | overhead scales as \(\approx2d^2\) per logical qubit |
| T states / T factories | magic states for non-Clifford gates | often >50 % of the total qubit budget |
| Runtime | wall-clock estimate | determines whether the attack/simulation is practical |
The \(T\)-factory insight. In a surface-code architecture, Clifford gates are cheap but \(T\) gates require magic-state distillation — dedicated factories consuming a large share of the chip. In the report above, 18 factories dominate the qubit count. This is why \(T\)-count is the standard cost metric in fault-tolerant algorithm design (L07), and why researchers work hard to reduce it.
What the estimator is for¶
# Compare QEC schemes at fixed algorithm
for scheme in [QECScheme.SURFACE_CODE, QECScheme.FLOQUET_CODE]:
...
# Compare qubit technologies
for qubit in [QubitParams.GATE_US_E3, # slow gates, 1e-3 error
QubitParams.GATE_NS_E4, # fast gates, 1e-4 error
QubitParams.MAJ_NS_E6]: # Majorana, 1e-6 error
...
This answers the questions that actually decide research directions:
- How much better must hardware get before this algorithm is useful?
- Is it worth reducing the \(T\)-count by 30 % at the cost of 2× more qubits?
- Which qubit technology reaches this application first?
42.6 Azure Quantum¶
import qsharp.azure
qsharp.azure.connect(resourceId="/subscriptions/.../Microsoft.Quantum/Workspaces/myws",
location="westus")
qsharp.azure.target("quantinuum.qpu.h1-1")
result = qsharp.azure.execute(RunGrover, n=3, marked=[True, False, True], shots=1000)
Targets available: Quantinuum (trapped ion, the highest-fidelity hardware commercially available), IonQ, Rigetti, Pasqal (neutral atom), plus Microsoft's simulators.
42.7 Solved Problems¶
Problem 1 — Translating a circuit into Q¶
Write a Q# operation implementing quantum teleportation (L10), with Adj + Ctl where appropriate.
Solution.
namespace Teleportation {
open Microsoft.Quantum.Intrinsic;
open Microsoft.Quantum.Measurement;
/// Teleports the state of `msg` onto `target`.
operation Teleport(msg : Qubit, target : Qubit) : Unit {
use here = Qubit(); // Alice's half of the EPR pair
// 1. Create the entangled pair (here, target)
H(here);
CNOT(here, target);
// 2. Alice's Bell measurement on (msg, here)
CNOT(msg, here);
H(msg);
// 3. Measure and apply the classically controlled corrections
if MResetZ(msg) == One { Z(target); }
if MResetZ(here) == One { X(target); }
}
@EntryPoint()
operation TestTeleport() : Result {
use (msg, target) = (Qubit(), Qubit());
// Prepare an arbitrary test state on msg
Ry(1.0472, msg); // pi/3 -> P(0) = 0.75
Teleport(msg, target);
Reset(msg);
return MResetZ(target); // should show P(0) ~ 0.75
}
}
Three Q# features doing real work here.
-
use here = Qubit();— the ancilla is scoped. It is measured withMResetZ, which returns it to \(|0\rangle\), satisfying Q#'s release requirement. Forgetting this is a compile/runtime error, not a silent bug. -
Teleportis not markedis Adj + Ctl. This is correct and important: it contains measurement, which is irreversible. The compiler would reject anis Adjannotation. In Qiskit, calling.inverse()on a circuit containing a measurement raises a runtime error only when you try it; Q# catches it at compile time. -
if MResetZ(msg) == One— genuine classical feed-forward within the quantum program, compiled to OpenQASM 3 conditionals or hardware-native branching.
Verification. With \(R_y(\pi/3)\), \(\Pr[0] = \cos^2(\pi/6) = 0.75\). Running 1000 shots of
TestTeleport should give ≈750 Zero — confirming the state arrived intact.
Problem 2 — Using functors to build a controlled operation¶
Show how much code Q# saves when building controlled modular multiplication for Shor's algorithm.
Solution.
In Q#.
operation ModularMultiply(a : Int, N : Int, target : Qubit[]) : Unit is Adj + Ctl {
// ... perhaps 200 lines of modular arithmetic ...
}
// Shor's algorithm then needs, for each of t counting qubits:
for i in 0 .. t - 1 {
Controlled ModularMultiply([counting[i]],
(ExpModI(a, 2^i, N), N, target));
}
Lines written for the controlled version: ZERO. The compiler generates it.
In Qiskit you must either:
- Write
modular_multiply_controlled()as a separate 200-line function, adding a control to every gate by hand, or - Use
circuit.to_gate().control(), which works but produces a highly inefficient decomposition — a naive control on every gate rather than an optimised controlled circuit — often inflating the gate count by 3–10×.
Quantitative comparison for Shor on a 2048-bit modulus.
| Q# | Qiskit (manual) | Qiskit (.control()) |
|
|---|---|---|---|
| Lines of code | ~200 | ~400 | ~200 |
| Bug surface | 1 implementation | 2 implementations to keep in sync | 1 |
| Gate count | optimised | optimised (if correct) | 3–10× inflated |
| Correctness guarantee | compiler-verified | manual review | automatic but wasteful |
The deeper point. Q#'s functors are not syntactic sugar. They encode a theorem: if an operation is expressed as a sequence of unitaries, its adjoint and controlled versions are mechanically derivable. The compiler applies that theorem, so the two versions cannot drift out of sync — which is exactly the bug that plagues hand-written quantum arithmetic.
Problem 3 — Reading a resource-estimation report¶
Interpret this report and answer the questions below.
Algorithm : Quantum chemistry, FeMoco active space
Logical qubits : 2,142
Logical depth : 4.7e10
T states : 3.2e11
Code distance : 21
Physical qubits/logical : 882
T factories : 14
T factory qubits : 1,900,000
Total physical qubits : 3,789,244
Runtime : 4.2 days
(a) What fraction of the qubits are used for magic-state distillation? (b) What happens if the physical error rate improves 10×? (c) Is this feasible today?
Solution.
(a) T-factory fraction.
Over half the machine exists solely to manufacture \(T\) states. This is typical, and it is the strongest argument for algorithmic work that reduces \(T\)-count.
(b) A 10× better physical error rate.
The surface code needs distance \(d\) satisfying, roughly,
Improving \(p_{\text{phys}}\) by 10× at fixed \(p_{\text{logical}}\) lets \(d\) shrink. Solving, \(d\) falls from 21 to roughly 11–13.
Since physical qubits per logical qubit scale as \(\approx 2d^2\):
Runtime also improves, since the surface-code cycle time scales with \(d\): roughly \(21/12 = 1.75\times\) faster, so about 2.4 days.
(c) Feasibility today.
| Required | Available (2024) | Gap | |
|---|---|---|---|
| Physical qubits | 3.8 million | ~1 000 (IBM Condor) | 3800× |
| Physical error rate | \(10^{-3}\)–\(10^{-4}\) | \(10^{-3}\) | met ✓ |
| Runtime | 4.2 days | — | acceptable |
Not feasible today. The qubit count is short by three to four orders of magnitude. At a historical doubling roughly every 1–2 years, closing a 3800× gap (\(\approx 2^{12}\)) takes 12–24 years.
But note what the report tells us that matters more than the verdict: the error rate is already adequate. The bottleneck is scale, not quality. That is a very different engineering problem from where the field stood in 2015, and it is exactly the kind of insight resource estimation exists to provide.
Problem 4 — Comparing Q# with a Python SDK¶
Implement the QFT in both Q# and Qiskit and compare the code, then explain when the extra ceremony of Q# pays for itself.
Solution.
Q# (from the standard library, Microsoft.Quantum.Canon):
operation QFT(qs : Qubit[]) : Unit is Adj + Ctl {
let n = Length(qs);
for i in 0 .. n - 1 {
H(qs[i]);
for j in i + 1 .. n - 1 {
Controlled R1([qs[j]], (PI() / IntAsDouble(2 ^ (j - i)), qs[i]));
}
}
SwapReverseRegister(qs);
}
Qiskit:
from qiskit import QuantumCircuit
import numpy as np
def qft(n):
qc = QuantumCircuit(n)
for i in range(n):
qc.h(i)
for j in range(i+1, n):
qc.cp(np.pi / 2**(j-i), j, i)
for i in range(n//2):
qc.swap(i, n-1-i)
return qc
Line counts are nearly identical. The difference appears the moment you need variants:
| Need | Q# | Qiskit |
|---|---|---|
| Inverse QFT | Adjoint QFT(qs) |
qft(n).inverse() — works ✓ |
| Controlled QFT | Controlled QFT([c], qs) |
qft(n).to_gate().control() — inefficient |
| Controlled inverse QFT | Controlled Adjoint QFT([c], qs) |
nested wrapping, very inefficient |
| Compile-time check that it is unitary | ✓ (the is Adj + Ctl annotation is verified) |
✗ |
When Q#'s ceremony pays for itself.
- Shor's algorithm — controlled modular exponentiation, inverse QFT. Q# wins clearly.
- Quantum chemistry — deeply nested Trotter steps, each needing controlled versions for phase estimation. Q# wins.
- Error correction — repeated syndrome extraction with classical feed-forward. Q# wins (its classical control is native).
- A 4-qubit VQC — no adjoints needed, and you want NumPy and matplotlib in the same file. Python SDK wins.
- Exploratory research — you want a Jupyter notebook and instant plotting. Python SDK wins.
The honest summary. Q# is an engineering language for building large, correct quantum programs. Python SDKs are research tools for rapid experimentation. Neither is better; they serve different phases of work — and Q# interoperates with Python, so a Q# operation can be called from a Jupyter notebook.
Problem 5 — Designing a resource-estimation study¶
You want to know when quantum computers will break RSA-2048. Design a resource-estimation study.
Solution.
Step 1 — Implement Shor's algorithm in Q# (or use Microsoft.Quantum.Samples.IntegerFactorization).
Only the structure matters, not the runtime — the estimator counts gates without executing them.
This is essential: no simulator could run 2048-bit Shor.
Step 2 — Sweep the qubit technology.
technologies = [
QubitParams.GATE_US_E3, # slow (us) gates, error 1e-3 -- trapped ion today
QubitParams.GATE_US_E4, # slow gates, error 1e-4 -- trapped ion, improved
QubitParams.GATE_NS_E3, # fast (ns) gates, error 1e-3 -- superconducting today
QubitParams.GATE_NS_E4, # fast gates, error 1e-4 -- superconducting, improved
QubitParams.MAJ_NS_E4, # Majorana, error 1e-4
QubitParams.MAJ_NS_E6, # Majorana, error 1e-6 -- speculative
]
Step 3 — Sweep the QEC scheme. Surface code versus Floquet code (which needs fewer qubits but requires Majorana hardware).
Step 4 — Tabulate.
| Technology | QEC | Physical qubits | Runtime |
|---|---|---|---|
| Gate ns, \(10^{-3}\) | surface | \(2.3\times10^{8}\) | 5.2 hours |
| Gate ns, \(10^{-4}\) | surface | \(2.2\times10^{7}\) | 4.1 hours |
| Gate µs, \(10^{-4}\) | surface | \(2.2\times10^{7}\) | 170 days |
| Majorana, \(10^{-4}\) | Floquet | \(9.4\times10^{6}\) | 3.8 hours |
| Majorana, \(10^{-6}\) | Floquet | \(1.8\times10^{6}\) | 2.9 hours |
(Figures are illustrative of the pattern the estimator produces.)
Step 5 — Draw the conclusions.
- Error rate dominates qubit count. Improving from \(10^{-3}\) to \(10^{-4}\) cuts qubits by 10×, because the required code distance falls.
- Gate speed dominates runtime. Trapped ions (µs gates) need the same qubit count as superconducting (ns gates) but take 1000× longer — 170 days versus 4 hours. For Shor, superconducting or Majorana hardware is essential; trapped ions are impractical regardless of their fidelity advantage.
- The binding constraint is qubit count, at \(10^{7}\)–\(10^{8}\) versus today's \(10^{3}\).
Step 6 — Project a timeline. At a doubling every 1–2 years, closing a \(10^{4}\) gap (\(\approx2^{13.3}\)) takes 13–27 years. Combined with independent expert surveys, this supports the common estimate of 2035–2045, with wide uncertainty.
Step 7 — Translate into a recommendation. Apply Mosca's inequality (L25): with \(Q \approx 20\) years and migration time \(M \approx 5\) years, any data needing confidentiality beyond \(Q - M = 15\) years must be protected with post-quantum cryptography today.
42.8 Practice Problems¶
- Write a Q# operation preparing the GHZ state on \(n\) qubits with
is Adj + Ctl. - Why can an operation containing a measurement not be marked
is Adj? - Rewrite
X(q); H(q); X(q);usingwithin/apply. - If \(d\) falls from 25 to 15, by what factor do the physical qubits per logical qubit fall? [Ans: 2.78×]
- What fraction of qubits are \(T\) factories in the Problem 3 report? [Ans: 50.1 %]
- When would you choose Q# over Qiskit? Give two scenarios.
- Explain why
userequires qubits to be released in \(|0\rangle\).
42.9 Summary¶
- Q# is a language, not a library: operations versus functions, scoped
use/borrowqubit allocation, and a type system that encodes quantum semantics. - Q# requires qubits to be released in \(|0\rangle\) — a runtime check that catches forgotten uncomputation, the most common silent bug in quantum programming.
- Functors are the signature feature:
Adjoint OpandControlled Opare compiler-generated and guaranteed correct, eliminating the duplicate hand-written implementations that plague Shor and chemistry circuits in Python SDKs. within/applyencodes the conjugation pattern \(UVU^\dagger\) so uncomputation cannot be forgotten.- The Azure Quantum Resource Estimator is Q#'s unique capability: physical qubits, runtime, code distance, \(T\)-state count and \(T\)-factory overhead for algorithms far too large to simulate.
- Reading such reports teaches the key facts: \(T\) factories often consume >50 % of the machine, a 10× better error rate buys ~3× fewer qubits, and gate speed dominates runtime while error rate dominates qubit count.
- Q# for large structured engineering; Python SDKs for exploratory research. They interoperate.
Next lesson: L43 — TensorFlow Quantum.
Practise now: unit4-platforms-lab.html → Resource Estimator: set qubit count, error rate and
\(T\)-count, and see code distance, physical qubits and runtime update live.