Code
- Constant oracle
- Balanced oracle
Step-by-step explanation
Gate definitionsx(Pauli-X / NOT):U(pi, 0, pi)— flips |0⟩ ↔ |1⟩.h(Hadamard):U(pi/2, 0, pi)— creates superposition.cx(CNOT): controlledU(pi, 0, pi)— used inside the balanced oracle.
oracle function differs:
constant(q0, q1)appliesx q1, which flips the ancilla unconditionally. This implements f(x) = 1 for all x — a constant function.balanced(q0, q1)appliescx q0, q1, which flips the ancilla only when q0 is |1⟩. This implements f(x) = x — a balanced function that outputs 0 and 1 for equal numbers of inputs.
reset. The ancilla qubit q1 is prepared in the |−⟩ state:
- Constant function: The ancilla flips regardless of q0. The phase factor (−1)^f(x) is the same for both terms in q0’s superposition, introducing a global phase that does not affect the measurement.
- Balanced function: The CNOT ties the ancilla flip to q0’s value. The relative phase between |0⟩ and |1⟩ in q0’s superposition flips sign, turning (|0⟩ + |1⟩)/√2 into (|0⟩ − |1⟩)/√2.
h q0 maps back from the Hadamard basis:
- If the oracle was constant: q0 → |0⟩
- If the oracle was balanced: q0 → |1⟩
Expected output
Measuring q0 after the final Hadamard gives a deterministic result:To switch between oracles, only the body of
oracle changes — constant(q0, q1) vs balanced(q0, q1). The surrounding circuit structure (initialization, final Hadamard) is identical in both cases.