An n-qubit register lives in a 2ⁿ-dimensional complex vector space: the state is a single list of 2ⁿ complex amplitudes, one per basis string like |01⟩, and every amplitude can in principle be nonzero at once. A gate on one qubit is really a 2×2 matrix expanded to the full 2ⁿ×2ⁿ space by a Kronecker (tensor) product with identities on every other qubit — this simulator applies that expansion directly: for a single-qubit gate it pairs up every basis index that differs only in the target qubit's bit and mixes those two amplitudes by the gate's 2×2 matrix, exactly like matrix multiplication restricted to the affected subspace. CNOT is a 4×4 matrix on a qubit pair: it swaps a pair of amplitudes whenever the control qubit's bit is 1, leaving everything else untouched.
H = 1/√2 [ 1 1 ] X = [ 0 1 ] Z = [ 1 0 ]
[ 1 -1 ] [ 1 0 ] [ 0 -1 ]
|ψ⟩ → (I ⊗ … ⊗ U ⊗ … ⊗ I) |ψ⟩ (single-qubit gate on qubit k)
CNOT: amp[i] ↔ amp[i ⊕ target-bit] whenever control-bit(i) = 1
Entanglement is what happens when a multi-qubit state can no longer be written as a product of independent single-qubit states — measuring one qubit then instantly constrains what the others must be. This simulator detects it honestly, not by a hardcoded flag: it partial-traces the full state down to qubit 0's 2×2 reduced density matrix ρ₀ and reports its purity Tr(ρ₀²). A purity of 1.0 means qubit 0 is still a clean, independent qubit; a purity of 0.5 is the minimum possible — the signature of maximal entanglement, exactly what H then CNOT produces (the Bell state (|00⟩+|11⟩)/√2).
- H — Hadamard: puts a qubit into an equal superposition of |0⟩ and |1⟩.
- X — bit-flip: swaps |0⟩ and |1⟩ (the quantum NOT).
- Z — phase-flip: leaves |0⟩ alone, multiplies |1⟩'s amplitude by −1.
- CNOT — flips the target qubit's bit only when the control qubit is |1⟩; applied after H, it correlates two qubits into an entangled pair instead of two independent coins.
- Measure — samples one basis outcome using the real Born-rule probabilities |amplitude|² and collapses the state vector to that outcome, exactly as a real projective measurement would.
Real-world relevance: this tensor-product state-vector method is precisely how classical quantum-circuit simulators (Qiskit's Statevector, Cirq) execute small circuits before a program ever touches real hardware — and the 2ⁿ growth you can feel here by adding a third qubit is the same exponential wall that makes simulating dozens of qubits classically intractable, which is the whole reason real quantum computers are useful.