Q# is a domain-specific language for high-level quantum algorithm design. Programs use .qs files, define quantum routines as operations, and can be paired with Python for preprocessing, postprocessing, and tests. Standalone programs run through the Azure Quantum Development Kit extension; a Python host or the extension selects a simulator or Azure Quantum hardware target. section 1.5 section 2.2.2
Qubits are allocated where needed with use and handled as Qubit variables. Gates are operations, usually from Std.Intrinsic, that change qubit state and return Unit. Before release, every allocated qubit must be returned to |0>; Reset measures it and conditionally applies X. This lifecycle matters when released qubits could be entangled with qubits still in use. section 2.1.3 section 2.3.4
Custom quantum operations can be called like built-in gates. An operation acting only on qubits and returning Unit can declare Adj and Ctl characteristics, allowing the compiler to generate adjoint, controlled, and controlled-adjoint variants. Adjoint and Controlled then produce those variants for use in larger constructions. section 2.3.4 section 2.5.3
Listing 2.2 Q# code to prepare a single-qubit state
import Std.Math.ArcTan2; #1
@EntryPoint() #2
operation SingleQubitDemo() : Unit { #3
use q = Qubit(); #4
let (alpha, beta) = (0.6, 0.8);
let theta = 2.0 * ArcTan2(beta, alpha); #5
Ry(theta, q); #6
Reset(q); #7
}
A minimal entry-point operation allocates one qubit, derives a rotation angle from target amplitudes, applies Ry, and resets the qubit for release. section 2.1.3
Simulation inspection is explicit: DumpMachine prints nonzero basis states with complex amplitudes, measurement probabilities, and phases. Tests can also use Python tooling to reconstruct an operation matrix and compare it with an expected unitary, including randomized cases. section 2.2.2 section 3.3.2
Q# supports practical quantum-programming patterns including:
- Recursive preparation of arbitrary multiqubit states from amplitude arrays, using controlled operations for branches. section 2.5.3
- Temporary auxiliary-qubit allocation inside an operation, as in parity measurement, followed by reset measurement. section 4.6.3
- Reversible implementations of single-bit and Boolean functions using X, CNOT, CCNOT, and controlled operations. section 6.2.3 section 6.4.3
- Algorithm components such as state-preparation routines and marking oracles for Grover search on the N queens puzzle. section 8.3.3
Reconstructing a state from trials
An operation can accept a state-preparation operation, repeatedly allocate and prepare a qubit, measure it with MResetZ, and use the trial counts to estimate coefficients. A second rotated measurement resolves the sign of one coefficient, keeping quantum execution and classical analysis together in Q#. section 4.5.3
