Skip to content
QVILLAGER logoQVILLAGER
OpenQASM 3.1

OpenQASM Quantum Circuits

From knowing nothing to being able to explain a circuit.

Saying 'it interferes' or 'it superposes' is not an explanation here. In the order result → numbers → figure → OpenQASM, confirm the same change from several viewpoints.

Beginner → Mastery~4 hour read19 chapters + Appendices A–E
OpenQASM 3.1Quantum circuitsBell statesGroverQAOA

Introduction

What to know first

This course is not a glossary of quantum mechanics. You will learn a quantum circuit as a procedure: prepare an input, operate on it, and read a 0 or 1 at the end. Rather than memorizing abstract words, the goal is to predict what happens when you run the same circuit many times.

The overall learning order

StageChaptersIntroduced for the first time here
A · ObserveCh. 0–20/1, circuits, measurement, shots, probability
B · StatesCh. 3–6amplitude, H, Z, interference, measurement bases
C · Multi-qubitCh. 7–9bit strings, CX, Bell states, entanglement
D · LanguageCh. 10–13OpenQASM declarations, arrays, control, modularization
E · HardwareCh. 14timing, barrier, noise, transpilation
F · AlgorithmsCh. 15–17Oracle, Grover, QUBO, QAOA
G · MasteryCh. 18migration, debugging, capstone

The single path through Chapters 13–18

Add one piece to the chain: input → change → output
ChapterWhat to look at firstReady to move on when…
13 RotationsSeparate probability, amplitude, and phase; compare RX, RY, RZ, and RZZYou can say that RZ changes phase, not immediate probability
14 HardwareSeparate logical/physical qubits, connections, SWAP, native gates, and pulsesYou can explain why the same Bell circuit becomes device instructions
15 OracleSeparate the problem condition, predicate, and OracleYou can say an Oracle marks phase; it does not output the answer
16 GroverTrace mark → diffusion → interference → measurementYou can say interference, not superposition alone, creates amplification
17 QAOATrace score → Cost phase → Mixer probability → measurementYou can separate the quantum circuit from the outer classical optimizer
18 DebuggingCheck grammar → ideal logic → hardware constraints → noiseYou can name the layer where a failure belongs first

The six-step template used throughout

  • •See the result: what you measure and how many 0s and 1s appear.
  • •Name it: attach new vocabulary only to an observed result or a calculation step.
  • •Follow the numbers: update the state's numbers one line at a time.
  • •Follow the circuit: trace the same operation from left to right.
  • •Follow the OpenQASM: trace the same operation from top to bottom.
  • •Predict: answer the result before running, then confirm it.

CHAPTER 00

Zeros, ones, circuits, and measurement

What kind of diagram is a quantum circuit?

0.1 Start with an ordinary bit

A bit in an ordinary computer is either 0 or 1 the instant you read it. A representative implementation reads low voltage as 0 and high voltage as 1. Here we ignore the physical method and use only 'an answer that is a single 0-or-1 digit'.

0.2 A quantum circuit also returns 0 or 1 at the end

A qubit can hold more states than a classical bit along the way. But when you measure it the usual way at the end, a single run yields just one answer, 0 or 1. The first key point is not to confuse the intermediate state with the answer you can finally read.

0.3 A circuit diagram is a timetable of operations

One horizontal line is the flow of time for one qubit. The left is the start, the right is the end. A box on the line is an instruction that changes the state at that point. You read 0/1 at the position of the measurement symbol.

Fig. 1Read a circuit from left to right: apply X to q[0], then measure.

0.4 OpenQASM writes the same procedure as text

Read the OpenQASM line by line

OpenQASM 3.1program
OPENQASM 3.1;
include "stdgates.inc";
qubit q;
bit result;
reset q;
result = measure q;
OPENQASM 3.1;Declares the language version in use
include "stdgates.inc";Makes the standard gate names available
qubit q;Prepares one qubit named q
bit result;Prepares a classical bit to hold the result
reset q;Prepares q as |0>, which will certainly measure as 0
result = measure q;Measures q and puts 0 or 1 into result

0.5 The first experiment

What to checkDetail
StartPrepare q as |0> with reset q;
OperationMeasure without applying a gate
ResultIdeally always 0
ReasonBecause q reads as 0 after reset

Check your understanding

  1. Which way does time flow in a circuit diagram?

    Show answer: Which way does time flow in a circuit diagram?

    It flows from left to right.

  2. How many answers does one standard measurement give?

    Show answer: How many answers does one standard measurement give?

    It gives exactly one answer: either 0 or 1.

  3. Are a qubit and a bit the same?

    Show answer: Are a qubit and a bit the same?

    No. A qubit has a quantum state before measurement; a bit stores the measured 0 or 1.

CHAPTER 01

Flipping 0 and 1 with the X gate

Fully predicting the simplest gate

1.1 First, just look at the result

Apply X once

What to checkDetail
Start|0>
OperationApply X once, then measure
ResultAlways 1
ReasonX swaps the state that reads as 0 for the one that reads as 1
InputAfter XMeasurement
|0>|1>1
|1>|0>0

1.2 Applying X twice

|0> → X → |1> → X → |0>. Because it returns to the start, X is its own inverse.

Read the OpenQASM line by line

OpenQASM 3.1program
OPENQASM 3.1;
include "stdgates.inc";
qubit q;
bit result;
reset q;
x q;
result = measure q;
x q;Applies the X gate to q once
result = measure q;Measures q after X, so ideally 1

Check your understanding

  1. What does |1> become after X?

    Show answer: What does |1> become after X?

    It becomes |0>.

  2. What appears if you apply X twice to |0> and measure?

    Show answer: What appears if you apply X twice to |0> and measure?

    The result is 0.

  3. What does the q in x q; represent?

    Show answer: What does the q in x q; represent?

    It is the name of the qubit to which X is applied.

CHAPTER 02

Telling one run from a thousand

Where does probability come from?

2.1 One result alone cannot tell you the ratio

To learn whether a given preparation tends to give 0 or 1, run the same program from the start many times. Each run is an independent experiment that prepares a fresh qubit.

Circuit1 shotIdeal tally over 1000 shots
Do nothing → measure00: 1000 times
X → measure11: 1000 times
H (learned later) → measure0 or 1about 500 each of 0 and 1

2.2 Separate the roles of OpenQASM and the execution service

OpenQASM describes 'what one program does'. Setting up a 1000-shot run, choosing the target simulator or hardware, and building the tally chart are usually the job of the SDK or execution service.

Check your understanding

  1. 1000 shots means doing what 1000 times?

    Show answer: 1000 shots means doing what 1000 times?

    Run the entire quantum program, from preparation through measurement, independently 1000 times.

  2. Where are shots usually specified relative to OpenQASM?

    Show answer: Where are shots usually specified relative to OpenQASM?

    They are usually configured in the SDK or execution service, not inside OpenQASM.

  3. What happens with an ideal X → measure over 1000 shots?

    Show answer: What happens with an ideal X → measure over 1000 shots?

    The result 1 appears 1000 times.

CHAPTER 03

Recording the pre-measurement state with two numbers

Why probability alone is not enough

3.1 The state card [a, b]

We record the pre-measurement state of one qubit with two numbers, [a, b]. The left value a is the 0-side number; the right value b is the 1-side number. In this course we use real numbers only, at first.

Fig. 2From the state card [a, b], square the amplitudes to get the 0/1 measurement probabilities.e.g. [1/√2, 1/√2] → [1/2, 1/2] → 50% each for 0 and 1. Amplitude and probability differ; probability is the amplitude squared.
StateState cardP(0)P(1)
|0>[1, 0]1² = 10² = 0
|1>[0, 1]0² = 01² = 1
50:50 example[1/√2, 1/√2](1/√2)² = 1/2(1/√2)² = 1/2

3.2 Don't fear √2

√2 is 'the positive number that squares to 2', about 1.414. 1/√2 is about 0.707, and squares to 1/2. So [1/√2, 1/√2] is a state card that gives 0 and 1 with 50% each.

3.3 A negative amplitude still gives a positive probability

For [1/√2, -1/√2] too, squaring gives 1/2 on both the 0-side and the 1-side. If you measure right away, plus versus minus is invisible in the count distribution. But later gates add and subtract amplitudes, so a difference in sign can turn into a different measurement result.

Check your understanding

  1. What is the measurement result of the state card [1,0]?

    Show answer: What is the measurement result of the state card [1,0]?

    The result is always 0.

  2. What is the square of 1/√2?

    Show answer: What is the square of 1/√2?

    It is 1/2.

  3. Does the amplitude −1/√2 mean a negative probability?

    Show answer: Does the amplitude −1/√2 mean a negative probability?

    No. Squaring its absolute value gives a probability of 1/2.

CHAPTER 04

Understanding the H gate through calculation

Not just a box that makes 50:50

4.1 The H rule has two parts

The H gate makes two new amplitudes from the input's 0-side amplitude a and 1-side amplitude b. The new 0-side is (a+b)/√2, and the new 1-side is (a−b)/√2. At first, just plug numbers into these formulas.

Fig. 3From input amplitudes a, b, H makes the new 0-side from the sum and the 1-side from the difference.

4.2 Apply H to |0>

The state card of |0> is [1,0]. The 0-side is (1+0)/√2 = 1/√2, and the 1-side is (1−0)/√2 = 1/√2. So H|0> = [1/√2, 1/√2]. Measuring gives 0 and 1 with 50% each.

4.3 Apply H to |1>

|1> is [0,1]. The 0-side is (0+1)/√2 = 1/√2, and the 1-side is (0−1)/√2 = −1/√2. So H|1> = [1/√2, −1/√2]. A standard measurement right after is still 50:50, but the sign differs.

Fig. 4Ideal measurement probabilities of |0>, |1>, and H|0>.
InputH calculationOutputStandard measurement
|0>=[1,0][(1+0)/√2,(1−0)/√2]|+>0/1 at 50:50
|1>=[0,1][(0+1)/√2,(0−1)/√2]|->0/1 at 50:50

Read the OpenQASM line by line

OpenQASM 3.1program
OPENQASM 3.1;
include "stdgates.inc";
qubit q;
bit result;
reset q;
h q;
result = measure q;
h q;Applies H to |0>=[1,0] to make |+>
measure0 or 1 in one shot; about 50:50 over many shots

4.4 Apply H twice

Apply H again to |+> = [1/√2, 1/√2]. The new 0-side is (1/√2 + 1/√2)/√2 = 1, and the new 1-side is (1/√2 − 1/√2)/√2 = 0. The result is [1,0] = |0>. H is also its own inverse.

Check your understanding

  1. What is the state card of H|0>?

    Show answer: What is the state card of H|0>?

    It is [1/√2,1/√2].

  2. Why is the 1-side amplitude of H|1> negative?

    Show answer: Why is the 1-side amplitude of H|1> negative?

    Because H's 1-side formula is (a−b)/√2, and |1> has a=0 and b=1.

  3. What happens if you apply H twice?

    Show answer: What happens if you apply H twice?

    The qubit returns to its original state.

CHAPTER 05

The Z gate and 'interference', from the numbers

Turning an invisible sign into a visible 0/1

5.1 The Z rule

The Z gate changes the state card [a,b] to [a,−b]. It leaves the 0-side unchanged and flips the sign of the 1-side amplitude only.

InputAfter ZStandard measurement right after
|0>=[1,0][1,0]Always 0
|1>=[0,1][0,-1]Always 1
|+>=[1/√2,1/√2][1/√2,-1/√2]=|->0/1 at 50:50

5.2 Why [0,−1] also measures as 1

Because P(0) = 0² = 0 and P(1) = (−1)² = 1. [0,−1] and [0,1], which differ by the same overall −, cannot be told apart by any measurement. On the other hand, [1/√2,1/√2] and [1/√2,−1/√2] differ in the sign relation between the two components, and a later H can tell them apart.

5.3 Compute H-Z-H line by line

PointState cardCalculation
Start[1,0]|0>
First H[1/√2,1/√2]|+>
Z[1/√2,-1/√2]|->
Last H[0,1]0-side=(a+b)/√2=0, 1-side=(a−b)/√2=1
Measure|1>Always 1
Fig. 5The state card at each stage of H-Z-H, and the two add/subtract steps in the final H.

5.4 Now, for the first time, we call it 'interference'

In the last H, to make the new 0-side amplitude we added 1/√2 and −1/√2. The result is 0. On the 1-side we subtracted −1/√2 from 1/√2, so the result is 1. When several amplitudes enter the amplitude calculation of the same output and grow or cancel to 0 through addition or subtraction, we call it interference.

Read the OpenQASM line by line

OpenQASM 3.1program
OPENQASM 3.1;
include "stdgates.inc";
qubit q;
bit result;
reset q;
h q;
z q;
h q;
result = measure q;
h q;[1,0]→[1/√2,1/√2]
z q;Flip the sign of the 1-side only
h q;Compute sum and difference to get [0,1]
measureIdeally always 1

Check your understanding

  1. How does Z change the state card [a,b]?

    Show answer: How does Z change the state card [a,b]?

    It changes it to [a,−b].

  2. Write the addition that makes the 0-side amplitude 0 in H-Z-H.

    Show answer: Write the addition that makes the 0-side amplitude 0 in H-Z-H.

    (1/√2 + (−1/√2))/√2 = 0.

  3. What is interference in this book?

    Show answer: What is interference in this book?

    Several amplitudes enter the calculation for the same output, and addition or subtraction changes their size.

CHAPTER 06

A measurement basis is 'what you distinguish when reading'

Understanding Z-basis and X-basis as circuits

6.1 A measuring device needs answer labels

A standard measure returns whether the state reads as |0> or |1>. But if you want to tell |+> from |->, place an H just before the standard measurement, because H|+> = |0> and H|-> = |1>.

Fig. 6The circuit difference between a Z-basis and an X-basis measurement.An X-basis measurement converts the reading with H first, then does a standard Z-basis measurement.
Prepared stateZ-basis measurementX-basis measurement (H → measure)
|0>Always 00/1 at 50:50
|1>Always 10/1 at 50:50
|+>0/1 at 50:50Always 0
|->0/1 at 50:50Always 1

Read the OpenQASM line by line

OpenQASM 3.1snippet
// Prepare |-> and measure in the X basis
x q;
h q;
// X-basis measurement
h q;
result = measure q;
x; h;Prepare |0>→|1>→|->
h; measureConvert |->→|1>, giving 1 in a standard measurement

Check your understanding

  1. What does a standard measure distinguish?

    Show answer: What does a standard measure distinguish?

    It distinguishes |0> from |1>.

  2. What do you place before measuring in the X basis?

    Show answer: What do you place before measuring in the X basis?

    Place an H gate before the measurement.

  3. What appears when you measure |+> in the X basis?

    Show answer: What appears when you measure |+> in the X basis?

    The result is always 0.

CHAPTER 07

Recording two qubits with four candidates

What do 00, 01, 10, 11 represent?

7.1 Two classical bits have four cases

Line up two bits and there are four cases: 00, 01, 10, 11. A two-qubit measurement result, in one shot, is also one of these four. With three qubits there are 2³ = 8 cases, from 000 to 111.

7.2 The two-qubit state card

For two qubits we line up four amplitudes, one for each candidate 00, 01, 10, 11. This book writes them in the order [q[0]q[1]], so the state card is [a00, a01, a10, a11].

StateState card [00,01,10,11]Measurement
|00>[1,0,0,0]Always 00
|01>[0,1,0,0]Always 01
00 and 10 at 50:50[1/√2,0,1/√2,0]00 or 10

7.3 Index order and display order are separate issues

This book writes bit strings in the order q[0]q[1]. However, an SDK or execution service may display the result string in the order q[1]q[0]. Don't guess the meaning; confirm the display rule with a minimal test that places a single X.

Fig. 7Apply X to q[0] only; whether the result reads 10 or 01 confirms the bit ordering.

Read the OpenQASM line by line

OpenQASM 3.1program
OPENQASM 3.1;
include "stdgates.inc";
qubit[2] q;
bit[2] c;
reset q;
x q[0];
c = measure q;
qubit[2] q;Prepare two qubits q[0] and q[1]
x q[0];In this book's order, |00>→|10>
c = measure q;Measure both; confirm the string order per environment

Check your understanding

  1. How many measurement candidates does a two-qubit system have?

    Show answer: How many measurement candidates does a two-qubit system have?

    It has four: 00, 01, 10, and 11.

  2. Write the 4-component state card of |01>.

    Show answer: Write the 4-component state card of |01>.

    It is [0,1,0,0].

  3. What is the minimal test to confirm the result-string order?

    Show answer: What is the minimal test to confirm the result-string order?

    Apply X to only one qubit, then measure both qubits.

CHAPTER 08

Understanding CX/CNOT with a four-row table

Don't mix up control and target

8.1 The rule is 'if the control is 1, apply X to the target'

Fig. 8The four CX inputs. Only on the two rows where the first-bit control is 1 does the second-bit target flip.
Input q[0]q[1]Control q[0]Target q[1]Output
000unchanged00
010unchanged01
1010→111
1111→010

8.2 Apply the same rule across the whole state card

When a state has amplitudes on multiple candidates, apply the four-row table to each candidate. For example, [1/√2,0,1/√2,0] is 00 and 10 at 50:50. Applying CX q[0],q[1] moves 00 to 00 and 10 to 11, giving [1/√2,0,0,1/√2].

Read the OpenQASM line by line

OpenQASM 3.1program
OPENQASM 3.1;
include "stdgates.inc";
qubit[2] q;
bit[2] c;
reset q;
x q[0];
cx q[0], q[1];
c = measure q;
x q[0];|00>→|10>
cx q[0],q[1];Control is 1, so target 0→1: |10>→|11>
measureIdeally 11

8.3 Swapping the arguments is a different circuit

For the same input |10>, cx q[1],q[0] does nothing because the control q[1] is 0, leaving |10>. The control and target lines cannot be exchanged.

Check your understanding

  1. What is the first argument of CX?

    Show answer: What is the first argument of CX?

    It is the control qubit.

  2. What do you get by applying cx q[0],q[1] to input 11?

    Show answer: What do you get by applying cx q[0],q[1] to input 11?

    The output is 10.

  3. What do you get by applying cx q[1],q[0] to input 10?

    Show answer: What do you get by applying cx q[1],q[0] to input 10?

    It stays 10 because the control q[1] is 0.

CHAPTER 09

Bell states and entanglement

Each qubit is 50:50, yet together they follow a rule

9.1 After H, apply CX

PointState card [00,01,10,11]Meaning
Start[1,0,0,0]Always 00
H q[0][1/√2,0,1/√2,0]Amplitudes on 00 and 10
CX q[0],q[1][1/√2,0,0,1/√2]The 10 amplitude moves to 11
Measure00 or 11Ideally 50% each
Fig. 9The Bell circuit: H makes amplitudes on 00/10, and CX moves the 10 amplitude to 11.

9.2 Look at 'each qubit alone' and it's 50:50

Since 00 and 11 are half each, q[0] alone is 0/1 at 50:50, and q[1] alone is 0/1 at 50:50. But looking at the two together, 01 and 10 never appear and the values always match. The individual ratios alone cannot express the overall relationship.

Fig. 10In a Bell state each qubit alone is 50:50, but measured together only 00 and 11 appear.

9.3 CX is not a copier of an unknown state

When the control is |0> or |1>, CX seems to align the target to the same Z-basis value. But if the control is |+>, the output is a Bell state, not 'control |+>, target |+>'. It has not made two copies of the same single-qubit state.

Read the OpenQASM line by line

OpenQASM 3.1program
OPENQASM 3.1;
include "stdgates.inc";
qubit[2] q;
bit[2] c;
reset q;
h q[0];
cx q[0], q[1];
c = measure q;
h q[0];Make equal amplitudes on 00 and 10
cx q[0],q[1];Move the 10 amplitude to 11
measureIdeally only 00 and 11

Check your understanding

  1. Which bit strings never appear from this Bell circuit?

    Show answer: Which bit strings never appear from this Bell circuit?

    01 and 10 never appear.

  2. What are the 0/1 ratios of each qubit alone?

    Show answer: What are the 0/1 ratios of each qubit alone?

    Each qubit gives 0 and 1 with 50% each.

  3. Can you communicate instantly with entanglement alone?

    Show answer: Can you communicate instantly with entanglement alone?

    No. You do not know the other side's result until you compare through classical communication.

CHAPTER 10

The skeleton of OpenQASM 3

Write declarations, operations, and measurement yourself

10.1 One line is, in principle, one statement

KindExampleRole
Version declarationOPENQASM 3.1;Specify the language version
Includeinclude "stdgates.inc";Define standard gate names
Quantum declarationqubit[2] q;Prepare two qubits
Classical declarationbit[2] c;Prepare two bits
Gateh q[0];Apply H to the target
Measurementc = measure q;Save the measurement result

10.2 Indices start from 0

For qubit[3] q; the usable indices are 0, 1, 2. q[3] means the fourth element, which is out of range. Distinguish the count 3 from the maximum index 2.

10.3 Comments are explanations that are not executed

OpenQASM 3.1snippet
// Everything to the right on this line is a line comment
x q[0];  // flip q[0]
/* A multi-line
   comment */

10.4 A complete Bell program

Read the OpenQASM line by line

OpenQASM 3.1program
OPENQASM 3.1;
include "stdgates.inc";
qubit[2] q;
bit[2] c;
reset q;
h q[0];
cx q[0], q[1];
c = measure q;
Lines 1–2Provide the language version and standard gates
Lines 3–4Declare two qubits and two result bits
Line 5Initialize the two qubits as |00>
Lines 6–7Prepare a Bell state
Line 8Measure both qubits

Check your understanding

  1. What is the maximum valid index for qubit[4] q;?

    Show answer: What is the maximum valid index for qubit[4] q;?

    It is 3, because indices start at 0.

  2. What is the main role of the semicolon?

    Show answer: What is the main role of the semicolon?

    It marks the end of a statement.

  3. What does include "stdgates.inc"; enable?

    Show answer: What does include "stdgates.inc"; enable?

    It makes standard gate names such as x, h, and cx available.

CHAPTER 11

Measurement, reset, and conditional branching

Read a 0/1 mid-circuit and change the operations that follow

11.1 Measurement is not only at the end

You can measure a qubit mid-circuit and save the result into a bit. Depending on whether that bit is 0 or 1, some systems let you change the later gates.

11.2 reset re-prepares to |0>

OpenQASM 3.1snippet
reset q[0];

11.3 Check a classical bit with if

OpenQASM 3.1snippet
bit m;
m = measure q[0];
if (m == 1) {
  x q[1];
}
mif conditionOperation on q[1]
0falsedo nothing
1trueapply X

11.4 Once measured, the original superposition does not remain

For example, measuring |+> gives 0 or 1. If the result is 0 the post-measurement state is |0>; if 1, it is |1>. Measuring the same qubit again with a standard measurement gives, ideally, the same value.

Check your understanding

  1. May you compare a qubit directly as q[0]==1 in an if?

    Show answer: May you compare a qubit directly as q[0]==1 in an if?

    No. Measure it first, save the result in a bit, and compare that bit.

  2. What is the ideal state after reset?

    Show answer: What is the ideal state after reset?

    It is |0>.

  3. What is the difference between a dynamic circuit and 1000 shots?

    Show answer: What is the difference between a dynamic circuit and 1000 shots?

    A dynamic circuit branches during one shot; shots independently repeat the entire program.

CHAPTER 12

Types, inputs, and loops

Trace an external input and a loop that operates on four qubits in sequence

12.1 A type decides how a value is used

TypeExampleUse
bit / bit[n]bit[3] c;0/1; measurement results and flags
boolbool done = false;true/false conditions
int / uintuint[8] count;integers; uint is nonnegative
floatfloat[64] score;numbers that may contain a fraction
angleangle theta;an angle that returns to the same direction after one turn
durationduration t = 100ns;time carrying a unit such as ns

12.2 input receives a value from outside the circuit

A complete program that returns 0 for flip=0 and 1 for flip=1

OpenQASM 3.1program
OPENQASM 3.1;
include "stdgates.inc";
input bit flip;
output bit result;
qubit q;
reset q;
if (flip == 1) {
  x q;
}
result = measure q;
input bit flip;Receive 0 or 1 from outside the program at run time
reset q;Initialize q as |0> before branching
if (flip == 1)Run X only when the received value is 1
result = measure q;Put the measured 0/1 into the output

Following flip from the entrance to the exit

Pass 0 and 1 into the same program and compare the paths that execute.

  1. STEP 1Pass flip in from outside

    The execution service passes 0 or 1 into flip. This is not a measurement result from a shot; it is an input chosen before execution.

    Type
    bit
    input bit flip;
  2. STEP 2Apply X only when flip=1

    If flip=0, q stays in |0>. If flip=1, X runs and q becomes |1>.

    flip=0
    result=0
    flip=1
    result=1
    if (flip == 1) {  x q;}
  3. STEP 3Return the measured value

    measure produces 0 or 1 and stores it in result. Only result, declared as output, is an explicit return value.

    result = measure q;

12.3 for is a repetition with a fixed count

OpenQASM 3.1snippet
qubit[4] q;
for int i in [0:3] {
  h q[i];
}

i changes as 0, 1, 2, 3, applying H once to each of the four qubits. [0:3] includes the endpoint 3.

Expand the for loop into four lines

A loop is not four operations happening magically at once; it is a sequence of instructions in which i changes value.

  1. i = 0Apply H to q[0]

    In this iteration i is 0, so h q[i]; acts as h q[0];.

    Actual statement
    h q[0];
    for int i in [0:3] {  h q[i];}
  2. i = 1Apply H to q[1]

    In this iteration i is 1, so h q[i]; acts as h q[1];.

    Actual statement
    h q[1];
    for int i in [0:3] {  h q[i];}
  3. i = 2Apply H to q[2]

    In this iteration i is 2, so h q[i]; acts as h q[2];.

    Actual statement
    h q[2];
    for int i in [0:3] {  h q[i];}
  4. i = 3Apply H to q[3]

    In this iteration i is 3, so h q[i]; acts as h q[3];.

    Actual statement
    h q[3];
    for int i in [0:3] {  h q[i];}

12.4 while repeats while the condition is true

OpenQASM 3.1snippet
qubit q;
bit success = 0;
while (success == 0) {
  reset q;
  h q;
  success = measure q;
}
Fig. 11The three places where repetition can happen

Check your understanding

  1. Where does flip in input bit flip; come from?

    Show answer: Where does flip in input bit flip; come from?

    It is passed at run time by an execution service or host outside the program.

  2. How many times does for int i in [0:3] run?

    Show answer: How many times does for int i in [0:3] run?

    Four times, with i=0, 1, 2, and 3.

  3. Are while and shots the same?

    Show answer: Are while and shots the same?

    No. while repeats conditionally within one run; shots independently repeat the whole program.

CHAPTER 13

Understand RX, RY, RZ, and RZZ through pictures

Read one-qubit rotations and two-qubit phase with one consistent map

13.1 Two maps for reading rotations

So far we treated amplitudes as real numbers and used only + and −. If you think of + as the 0° direction and − as the 180° direction, the sign is two special cases of phase. General quantum circuits also use intermediate directions such as 45° or 90°.

Clock directionDegreesRadians
Right0°0
Up90°π/2
Left180°π
One full turn, back to the right360°2π
Fig. 12Read a complex amplitude as a clock hand

Compare four rotation gates with the same questions

All three turn an arrow through the sphere's center. What differs is the axis they turn around. Compare the X, Y, and Z axes with the arrow's destination.

RYMoves the 0/1 share

Turns around Y. At π/2 the arrow reaches +X and measurement is 50:50.

RXSame share, different direction

Turns around X. At π/2 the arrow reaches −Y, yet measurement is also 50:50.

RZTurns direction, keeps the share

First H makes 50:50; then RZ changes only phase by turning around Z.

RY

Move the likelihood of 0 and 1 directly

1 qubit
What it changes
The share of amplitude on the 0 and 1 sides
What it does not change immediately
The ideal total probability of 1
Example
Apply RY(π/2) to |0>, and 0 and 1 each become 50% likely.
OpenQASM
ry(pi / 2) q;
Later use
Use it to prepare an input or trial probability from an angle.

RX

Reach the same likelihoods from another direction

1 qubit
What it changes
The 0/1 share and the direction of the 1-side amplitude
What it does not change immediately
For key angles from |0>, the measurement probabilities match RY
Example
RX(π/2) on |0> is also 50:50, but the 1-side amplitude points in the −i direction.
OpenQASM
rx(pi / 2) q;
Later use
In Chapter 17 it becomes the QAOA Mixer that turns phase differences into likelihoods.

RZ

Turn the clock without changing likelihoods

1 qubit
What it changes
For positive θ, the phase-clock arrow for 0 turns clockwise by θ/2, while 1 turns counter-clockwise by θ/2
What it does not change immediately
Immediate 0/1 probability in the Z basis
Example
Starting from phase 1 (pointing right), RZ(π) sends the 0 side to −i and the 1 side to +i. Probabilities stay 50:50; a final H then makes 1 appear with 100% probability.
OpenQASM
rz(pi) q;
Later use
Use it to leave a phase mark and as the middle operation inside RZZ.

RZZ

Compare two bits and mark candidates with arrow directions

2 qubits
What it changes
The four candidates' arrow directions; matching and different pairs point different ways
What it does not change immediately
The candidates 00, 01, 10, and 11 and each one's measurement probability
Example
For θ=90°, arrows for 00/11 point down-right and arrows for 01/10 point up-right. All four probabilities stay at 25%.
OpenQASM
cx a,b; rz(theta) b; cx a,b;
Later use
In Chapter 17 it becomes the QAOA Cost circuit that maps a two-variable score into phase.

13.2 RY moves continuously from 0 to 1

Applying RY(θ) to |0> gives cos(θ/2)|0> + sin(θ/2)|1>. θ=0 gives |0>, θ=π/2 gives 0/1 at 50:50, and θ=π gives |1>. π is 180°, so π/2 is 90°.

θRY(θ)|0>P(1)
0|0>0
π/2(|0>+|1>)/√21/2
π|1>1
Fig. 13Measurement probabilities as the RY angle moves from 0 to π

A complete program that receives the RY angle from outside

OpenQASM 3.1program
OPENQASM 3.1;
include "stdgates.inc";
input angle theta;
output bit result;
qubit q;
reset q;
ry(theta) q;
result = measure q;
input angle theta;Receive 0, pi/2, pi, or another angle at run time
reset q;Start every angle from the same |0> state
ry(theta) q;Rotate |0> according to theta
result = measure q;The ideal probability of 1 is sin²(theta/2)

13.3 Read RZ's invisible difference with H

GateOpenQASMMainly changes
RXrx(theta) q;0/1 amplitude and phase
RYry(theta) q;0/1 amplitude; easy to follow with reals
RZrz(theta) q;the relative phase of one qubit
ZZ phasecx a,b; rz(theta) b; cx a,b;phase based on the two-qubit relation

A complete program that turns RZ's phase difference into 1 with H

OpenQASM 3.1program
OPENQASM 3.1;
include "stdgates.inc";
output bit result;
qubit q;
reset q;
h q;
rz(pi) q;
h q;
result = measure q;
reset q;Initialize q as |0>
h q;|0>→|+>; the 0-side and 1-side amplitudes point in the same direction
rz(pi) q;Separate the two components by 180°; after ignoring the shared phase, this is |->
h q;|->→|1>; convert the phase difference into a measurable difference
measureIdeally always 1

Use the final H to read phase that RZ alone leaves invisible

Check H-RZ(π)-H by alternating between state cards and amplitude directions.

  1. STEP 1Start in |0>

    Reset prepares |0>. Only the 0-side amplitude is 1, so a standard measurement would always return 0.

    Measurement
    0 at 100%
    qubit q;reset q;
  2. STEP 2Make |+> with H

    The 0-side and 1-side have the same magnitude and point in the same 0° direction.

    State
    |+>
    h q;
  3. STEP 3Use RZ(π) to point the two arrows in opposite directions

    RZ(π) turns the 0 side 90° clockwise and the 1 side 90° counter-clockwise. Their separation changes from 0° to 180°, so they point oppositely. Their lengths do not change, so measuring immediately still gives 0 and 1 at 50:50.

    What RZ changed
    direction gap 0° → 180°
    What is still unchanged
    0/1 probability 50:50
    rz(pi) q;
  4. STEP 4Add and subtract the arrows at H's two outputs

    H has a 0 output that adds the two arrows and a 1 output that subtracts the 1 side from the 0 side. At the 0 output, opposite arrows cancel. At the 1 output, subtracting a left arrow turns it into a right arrow, so the two arrows reinforce each other. The amplitude therefore remains only on the 1 side.

    Measurement
    1 at 100%
    h q;result = measure q;

13.4 Apply phase to a two-qubit relation with CX-RZ-CX

The first CX flips b only when a is 1. Listing all four cases shows that the temporary b after CX is 0 when a and b match and 1 when they differ. In other words, b becomes a temporary one-bit note that records ‘same or different’.

Fig. 14Following all four candidates row by row shows why CX-RZ-CX equals RZZ
Fig. 15Write the four-row process above with quantum-circuit symbols

13.5 gate names a sequence of quantum operations

OpenQASM 3.1snippet
gate zz_phase(theta) a, b {
  cx a, b;
  rz(theta) b;
  cx a, b;
}
qubit[2] q;
zz_phase(pi / 2) q[0], q[1];
DEEP DIVERead after the rotations make sense: modifiers and defThese OpenQASM modularization features are useful, but they are not required to understand the four rotation gates.

13.6 Modifiers change how an existing gate is used

ModifierExampleMeaning
ctrl @ctrl @ x q[0],q[1];controlled X, i.e. CX
negctrl @negctrl @ x a,b;apply when the control is 0
inv @inv @ s q;the inverse of S
pow(k) @pow(2) @ t q;equivalent to applying T twice

13.7 def is a general subroutine

OpenQASM 3.1snippet
def parity(bit[4] x) -> bit {
  bit p = 0;
  for int i in [0:3] {
    p ^= x[i];
  }
  return p;
}

p ^= x[i]; computes XOR and stores the result back in p. XOR is 1 when p and x[i] differ and 0 when they match. After four iterations, p=1 exactly when x contains an odd number of 1s; p=0 when that number is even. This computes parity rather than the count itself, so it uses def rather than gate, which groups quantum gates only.

Comparisongatedef
Main purposea unitary sequence of quantum gatesgeneral processing
Return valuenonecan have one
Measurement / classicalgenerally unsuitablecan handle it
Inverse modifiergenerally possiblenot generally treated the same way

Check your understanding

  1. What is 90° in radians?

    Show answer: What is 90° in radians?

    It is π/2, which OpenQASM can write as pi / 2.

  2. What are the Z-basis measurement probabilities immediately after applying RZ(π) to |+>?

    Show answer: What are the Z-basis measurement probabilities immediately after applying RZ(π) to |+>?

    They remain 50% for 0 and 50% for 1. A later H turns the phase difference into a measurement result.

  3. Why is the final CX present in CX-RZ-CX?

    Show answer: Why is the final CX present in CX-RZ-CX?

    It restores the temporary relation copied by the first CX, leaving only the phase change.

  4. Should classical processing that returns a value use gate or def?

    Show answer: Should classical processing that returns a value use gate or def?

    It should use def.

CHAPTER 14

From a logical circuit to real-hardware execution

Watch the same Bell circuit become a layout, SWAPs, native gates, and pulses

14.1 Start with the Bell circuit that expresses our intent

Throughout this chapter we follow the same example: a Bell state made with H and CX. The q[0] and q[1] we write are not yet component numbers on a device. At first they express only the logic: apply H, then CX, and aim to obtain 00 or 11.

A complete program for the Bell circuit before conversion

OpenQASM 3.1program
OPENQASM 3.1;
include "stdgates.inc";
output bit[2] result;
qubit[2] q;
reset q;
h q[0];
cx q[0], q[1];
result = measure q;
qubit[2] q;Two logical qubits whose physical numbers are not fixed yet
reset q;Initialize the logical circuit's starting state as |00>
h; cx;The logic that prepares a Bell state
measureIdeally, about half 00 and half 11

Why not connect physical 0 directly to physical 2? On real hardware, a two-qubit operation such as CX is allowed only for pairs with a physical coupling (a direct link). If the device is 0–1–2, 0 and 2 cannot talk by jumping over 1. This is not like broadcasting a classical signal over a longer wire: the two-qubit gate itself is supported only on adjacent pairs. The compiler can choose another layout, move a state with SWAPs, or use another decomposition. We use SWAP here because it makes the routing idea visible.

Why CX works after SWAP on a 0–1–2 device
StageContents of physical 0Contents of physical 1Contents of physical 2
Beforestate of q[0]empty / another statestate of q[1]
After SWAP 0,1other statestate of q[0]state of q[1]
Next CXnot usedcontroltarget
SWAP = CX(A→B) → CX(B→A) → CX(A→B)
Input (A,B)After 1After 2After 3
00000000
01011110
10110101
11101011

How the Bell circuit reaches the device

The logic stays the same, but the circuit's appearance and instruction count change for the target device.

  1. STEP 1Write the logical circuit

    Apply H to q[0], then use q[0] as the control of CX on q[1]. At this stage the goal is the 00/11 correlation.

    Ideal distribution
    00:50%, 11:50%
    h q[0];cx q[0], q[1];
  2. STEP 2Lay logical qubits onto physical qubits

    As an example, place q[0] on physical 0 and q[1] on physical 2. If the device connects 0–1–2, CX is supported only on the directly linked pairs 0–1 or 1–2. This device has no long-range CX that jumps from 0 to 2.

    Direct links
    0–1 and 1–2
  3. STEP 3Move next door with SWAP, then apply CX

    SWAP exchanges the contents of physical 0 and 1. q[0]'s state moves to physical 1 while q[1]'s state stays at physical 2, so the adjacent pair 1–2 can perform CX. This does not send q[0] directly to physical 2; it takes one step because no 0-to-2 link exists. The compiler also updates the final measurement mapping.

    Added operation
    SWAP
  4. STEP 4Decompose into the device's native gates

    If the device cannot execute SWAP directly, replace it with CX(A→B)→CX(B→A)→CX(A→B). The first CX temporarily changes B, the second hands A's original value to A's partner, and the third hands A's original value to B. This works because CX is a native instruction on the device. Gate count and depth increase compared with the logical circuit.

    One SWAP
    Can decompose into three CX gates
  5. STEP 5Execute calibrated pulses

    Finally, each native gate is played as a physical signal calibrated for its target qubits. Hardware errors and elapsed time now affect the result.

    Output
    Hardware measurement counts
Fig. 16Five stages from the logical Bell circuit to hardware control

14.2 Separate barrier, delay, and pulse on the timeline

OpenQASM 3.1snippet
h q[0];
barrier q;
cx q[0], q[1];
OpenQASM 3.1snippet
delay[100ns] q[0];
Fig. 17What barrier, delay, and pulse each represent

14.3 Tell shot fluctuation from noise by which candidates appear

An ideal Bell state has only the candidates 00 and 11. With 100 shots their ratio may fluctuate to 46 versus 54, but an ideal run still never produces 01 or 10. If 01 and 10 repeatedly appear on hardware, finite shots alone cannot explain them, so investigate gate and readout errors.

Fig. 18An ideal distribution, finite-shot fluctuation, and a distribution containing noise

Check your understanding

  1. What may a transpiler add when physical 0 and physical 2 are not directly connected?

    Show answer: What may a transpiler add when physical 0 and physical 2 are not directly connected?

    It may add a SWAP to move the state to an adjacent qubit.

  2. Does barrier prevent noise or flip the ideal state?

    Show answer: Does barrier prevent noise or flip the ideal state?

    No. It is a boundary that restricts gate movement and merging for specified qubits.

  3. If 100 shots of an ideal Bell circuit give 00:46 and 11:54, does that immediately prove a fault?

    Show answer: If 100 shots of an ideal Bell circuit give 00:46 and 11:54, does that immediately prove a fault?

    No. It can be a natural fluctuation from a finite number of shots.

  4. If a Bell circuit repeatedly produces 01 and 10, what should you compare first?

    Show answer: If a Bell circuit repeatedly produces 01 and 10, what should you compare first?

    Return to the state calculation and ideal-simulator distribution, then isolate hardware noise.

CHAPTER 15

Separating algorithms, circuits, and Oracles

Starting from a predicate table, phase-flip only candidate 10 out of four

There are two things to track in this chapter: the candidate labels and the direction of each amplitude. H prepares the four candidates, the Oracle changes only 10 from +1/2 to −1/2, and we do not measure yet. The Oracle is therefore not an operation that displays the answer; it writes a mark that a later amplification step can use.

15.1 First separate what you solve from how you run it

In this chapter, we search the candidates 00, 01, 10, and 11 for one that matches a condition. The condition is ‘the left bit is 1 and the right bit is 0.’ Instead of storing the answer 10 directly in a box, we build a predicate rule that can be applied equally to every candidate.

Separate who knows what
RoleWhat it doesIn this example
Problem setupDefines the condition to search forleft=1 and right=0
Predicate fChecks one candidate and returns 0 or 1f(10)=1, all others=0
GroverUses f to amplify matching candidatesMake 10 easier to measure
Classical search versus Grover (one Oracle call costs 1 unit)
Number of candidates NClassical searchGrover (ideal scale)What you see
4about 2 on average / 4 worst case√4-scaleSmall difference; good for teaching
1,000,000about 500,000 on average / 1,000,000 worst caseabout 1,000-scaleThe gap appears for large N
What N=4, one iteration, and 100 shots mean
TermWhat it countsThis example
Number of candidates NCandidates placed in the superposition4: 00, 01, 10, 11
Grover iterationOne Oracle → diffusion block1
ShotOne complete circuit run + measurement100
Final resultThe distribution collected from 100 measurementsIdeally about 100% 10
LayerExample in this chapterQuestion it answers
ProblemFind a match among four candidatesWhat are we solving?
Predicate functionReturn 1 when left=1 and right=0How is a candidate judged?
AlgorithmEqualize → mark → amplify → measureWhat procedure finds it?
Quantum circuitH, Oracle, and diffusionWhich gate sequence runs it?
OpenQASMh, x, cz, …How is the circuit written as text?
Fig. 19The five layers from a problem to OpenQASM

15.2 Fix the predicate f(x) with four rows

The condition is ‘q[0]=1 and q[1]=0’
Candidate x=q[0]q[1]Is the left bit 1?Is the right bit 0?f(x)
00NoYes0
01NoNo0
10YesYes1 ← matches
11YesNo0

15.3 Mark only 10 with X–CZ–X

CZ flips only the amplitude of 11. To mark 10, first apply X to q[1] so that 10 temporarily moves to 11, use CZ to flip its sign, and apply X again to restore the candidate label to 10. The other candidates are also temporarily exchanged, but only the original 10 reaches the location affected by CZ.

Complete program that phase-marks 10

OpenQASM 3.1program
OPENQASM 3.1;
include "stdgates.inc";
output bit[2] result;
qubit[2] q;
reset q;
h q;
x q[1];
cz q[0], q[1];
x q[1];
result = measure q;
reset q;Initialize the two qubits as |00>
h q;Prepare 00, 01, 10, and 11 with amplitude +1/2 each
x q[1];Temporarily move the target 10 to the 11 position
cz q[0], q[1];Flip only the original 10 now located at 11
x q[1];Restore the original candidate labels
measureWith only the Oracle, all four candidates are still 25%

From the predicate table to a phase mark

Keep candidate 10 highlighted while connecting the rule, gates, and amplitudes.

  1. STEP 1Evaluate f(10)=1

    Apply the same condition, ‘left=1 and right=0,’ to all four candidates. Only 10 returns 1.

    Matching candidate
    10
  2. STEP 2Use H to make four equal candidates

    Applying H to both qubits makes all four amplitudes +1/2. Every candidate has probability 25%.

    Probability of each candidate
    25%
    h q;
  3. STEP 3Run X–CZ–X

    X on q[1] moves 10 to 11, CZ flips its sign, and the final X restores its label.

    x q[1];cz q[0], q[1];x q[1];
  4. STEP 4Only 10’s amplitude becomes −1/2

    The candidate labels are back in their original order. Only the direction of 10’s amplitude changed, so every measurement probability is still 25% at this point.

    State card
    [1/2, 1/2, −1/2, 1/2]

Check your understanding

  1. What does the predicate function f(x) return?

    Show answer: What does the predicate function f(x) return?

    It returns 1 when candidate x satisfies the condition and 0 when it does not.

  2. Why place x q[1]; before and after the CZ that marks 10?

    Show answer: Why place x q[1]; before and after the CZ that marks 10?

    The first X temporarily moves 10 to the 11 position that CZ marks, and the second X restores the candidate labels afterward.

  3. What is the measurement probability of 10 immediately after the Oracle?

    Show answer: What is the measurement probability of 10 immediately after the Oracle?

    25%. Its amplitude changes from +1/2 to −1/2, but the squared magnitude remains 1/4.

  4. Is an Oracle a box that outputs answer 10 before the search begins?

    Show answer: Is an Oracle a box that outputs answer 10 before the search begins?

    No. It is a circuit implementation of a predicate rule that can be applied to all four candidates.

CHAPTER 16

Computing Grover completely with four candidates

Turn the −1/2 mark into an amplitude that makes 10 appear with 100% probability

16.1 Connect every line from reset to measure

Here we follow the code without gaps from the first reset to the final measure, explaining both what happens on each line and why it happens. Keep the candidate order fixed as [00,01,10,11], and use that same order for every amplitude list.

The complete QASM from reset to measurement

OpenQASM 3.1program
OPENQASM 3.1;
include "stdgates.inc";

output bit[2] result;
qubit[2] q;

reset q;

// Equalization
h q;

// Oracle: mark 10
x q[1];
cz q[0], q[1];
x q[1];

// Diffusion
h q;
x q;
cz q[0], q[1];
x q;
h q;

result = measure q;

Complete calculation: follow the code line by line

This is the chapter's detailed path. Keep the execution order and follow labels, phases, and interference one step at a time.

  1. LINE 1Start from |00>

    Set q[0] and q[1] to |00>. The amplitudes are [1,0,0,0], so measuring now would return 00 with 100%. A fixed starting point makes later comparisons meaningful.

    Measurement
    00 with 100%
    reset q;
  2. LINE 2Equalize the four candidates

    Apply H to both qubits. Each 0 branches into 0 and 1, so every bit string receives +1/2. This is equalization.

    State card
    [+1/2,+1/2,+1/2,+1/2]
    h q;
  3. LINE 3Move 10 to the 11 position

    Flipping q[1] swaps 00↔01 and 10↔11. Original 10 temporarily sits at 11. Locations move, but signs do not, because CZ can see only 11.

    Original target
    10→11
    x q[1];
  4. LINE 4Flip only 11’s phase

    CZ does not move labels; it multiplies only 11 by −1. That amplitude came from original 10, so original 10 alone changes from +1/2 to −1/2. Only direction changes, not probability.

    CZ rule
    Flip 11’s sign only
    cz q[0], q[1];
  5. LINE 5Restore the label and finish the Oracle

    Flip q[1] again, returning the negative amplitude from 11 to 10. The Oracle changed only 10’s phase; all four probabilities are still 25%.

    State card
    [+1/2,+1/2,−1/2,+1/2]
    x q[1];
  6. LINE 6Expand the phase difference

    H acts on both qubits at the same time. Use the two one-qubit rules to make four contributions, then add terms that point to the same output column. In the diagram, each row is one original term's contribution and each column is one final output.

    h q;
  7. LINE 7Move signed amplitudes together

    The mappings are 00↔11 and 01↔10. A sign travels with its amplitude. For example, the negative amplitude at 01 becomes the negative amplitude at 10. X changes labels, not the phase mark.

    After X
    [+1/2,+1/2,−1/2,+1/2]
    x q;
  8. LINE 8Flip the current 11

    The diffusion CZ leaves labels in place and turns the current positive 11 negative. Here the 11 flip is part of the circuit that implements inversion about the mean.

    After CZ
    [+1/2,+1/2,−1/2,−1/2]
    cz q[0], q[1];
  9. LINE 9Restore the labels again

    Flip both bits again. The negative 11 goes to 00 and the negative 10 goes to 01. The final H will combine this arrangement through interference.

    After X
    [−1/2,−1/2,+1/2,+1/2]
    x q;
  10. LINE 10Final interference leaves only 10

    Expand each input with H and add by output column. The 00, 01, and 11 columns cancel. In the 10 column, all four contributions are −1/4, so they add constructively to −1.

    Final state
    [0,0,−1,0]
    h q;
  11. LINE 11Measure 10

    Measurement probabilities are squared amplitude magnitudes. Only 10 has |−1|²=1, so an ideal run returns 10 with 100%. The Oracle’s phase difference became a measurable amplitude difference through diffusion.

    Probability
    P(10)=1
    result = measure q;
Review: five checkpoints
CheckpointAmplitudes [00,01,10,11]What to confirm
After reset[1,0,0,0]Start from known |00>
After equalization[+1/2,+1/2,+1/2,+1/2]Each candidate has 25% probability
After the Oracle[+1/2,+1/2,−1/2,+1/2]Only 10 changes phase; probabilities remain 25%
After diffusion[0,0,−1,0]Only 10 has amplitude magnitude 1
Measurement10Ideal probability 100%

16.2 Check the same diffusion using the 'mean as a mirror' view

The mean after the Oracle is m=(1/2+1/2−1/2+1/2)/4=1/4. 'About the mean' means moving a value the same distance from one side of the mean to the other. A value below the mean moves the same distance above it. The representative formula is new amplitude = 2m−old amplitude.

CandidateOld amplitude x2m−x (2m=1/2)New amplitude (representative)
001/21/2−1/20
011/21/2−1/20
10 correct−1/21/2−(−1/2)1
111/21/2−1/20
Fig. 20Move all four amplitudes across the mirror at mean 1/4

16.3 Too many repetitions lower the success rate

In general, for N candidates and M correct answers, the Oracle and diffusion are repeated on the order of √(N/M) times. But the successful amplitude does not rise forever; overshooting makes it fall again. For this N=4, M=1 example, one iteration is optimal.

Number of Oracle+diffusion iterationsIdeal probability of 10Decision
025%Still uniform
1100%Measure here
225%Overshot

Check your understanding

  1. What is the state card immediately after the Oracle?

    Show answer: What is the state card immediately after the Oracle?

    [1/2,1/2,−1/2,1/2], in candidate order [00,01,10,11].

  2. What is the mean m of the four post-Oracle amplitudes?

    Show answer: What is the mean m of the four post-Oracle amplitudes?

    1/4.

  3. What is the representative amplitude 2m−x for candidate 10?

    Show answer: What is the representative amplitude 2m−x for candidate 10?

    2×1/4−(−1/2)=1. The displayed circuit’s direct value −1 differs only by global phase.

  4. Should this two-bit example apply the Oracle and diffusion twice?

    Show answer: Should this two-bit example apply the Oracle and diffusion twice?

    No. One iteration gives 10 a 100% probability, and a second lowers it back to 25%.

CHAPTER 17

From QUBO to a QAOA circuit

Separate the Cost that maps score to phase from the Mixer that changes likelihood

QAOA is not the name of one gate. It is a framework that repeats a pattern: prepare all candidates, use Cost to change the directions of good and bad candidates, use Mixer to mix candidates, and measure. A classical program outside the quantum circuit chooses new γ and β values after looking at the measurement scores.

17.1 Act 1: Give every candidate a score

Consider the smallest MaxCut: divide two people into different groups. x0 and x1 are each 0 or 1, with 0 meaning group A and 1 meaning group B. Different groups score 1; the same group scores 0. The two optimal candidates are 01 and 10.

Candidate x0x1GroupsSame/differentScore C
00A · ASame0
01A · BDifferent1 ← optimal
10B · ADifferent1 ← optimal
11B · BSame0

17.2 The QUBO formula preserves all four scores

The score can be written as C(x)=x0+x1−2x0x1. Do not memorize it as an opaque formula; substitute all four candidates and verify that it matches the table above.

x0x1x0+x1−2x0x1C
000+0−2×0×00
010+1−2×0×11
101+0−2×1×01
111+1−2×1×10
DEEP DIVEDerive the Ising expression and the sign of RZ from QUBOFor readers who want to verify the same Cost→Mixer circuit with equations after understanding the main path.

17.3 Map 0/1 values to Z’s +1/−1 values

The quantum Z operator associates +1 with |0> and −1 with |1>. Set z=1−2x, or inversely x=(1−z)/2. Substitution gives C=(1−z0z1)/2. The candidates do not change; only the way their values are written changes.

x0x1z0,z1Product z0z1(1−z0z1)/2Score
00+1,+1+100
01+1,−1−111
10−1,+1−111
11−1,−1+100
Fig. 21Translate a score table into a Cost circuit without changing what the candidates mean

17.4 Act 2: Use a Mixer to turn Cost phases into probabilities

Fig. 22Cost maps score to clock direction, not directly to probability
For γ=π/2, these two rows are enough to follow Cost without evaluating exponentials
Score Ce^{-iγC}Amplitude direction
0 (00 and 11)e^0 = 1Stays at 0°
1 (01 and 10)e^{-iπ/2} = −iRotates to −90°

Run γ=π/2 and β=π/8 exactly once

At these angles, all probability moves to the optimal candidates 01 and 10.

  1. STEP 1Use H to equalize four candidates

    Starting from |00> after reset, create a uniform state in which every amplitude is +1/2.

    State
    [1/2,1/2,1/2,1/2]
    h q;
  2. STEP 2Cost(π/2) gives score-1 candidates a −90° phase

    For this example, use the rule 'score 0 does not turn the clock; score 1 turns it by −90°'. Thus 00 and 11 stay at 0°, while 01 and 10 point at −90°. Every arrow still has length 1/2, so every probability remains 25%. The deep dive above explains why the RZ angle has a minus sign.

    γ
    π/2
    cx q[0], q[1];rz(-gamma) q[1];cx q[0], q[1];
  3. STEP 3Mixer(π/8) turns phase differences into probabilities

    Applying RX(π/4) to each qubit makes the amplitudes of 00 and 11 zero and gives the amplitudes of 01 and 10 magnitude 1/√2.

    β
    π/8
    Mean score
    1
    rx(2 * beta) q;
  4. STEP 4Measure and calculate the score

    Ideally, only 01 or 10 appears. Both have score 1, so the mean score at these angles is 1.

    Maximum score
    1

Complete OpenQASM for a two-variable, one-layer QAOA

OpenQASM 3.1program
OPENQASM 3.1;
include "stdgates.inc";
input angle gamma;
input angle beta;
output bit[2] result;
qubit[2] q;
reset q;
h q;
// U_C(gamma): e^{-i gamma C}
cx q[0], q[1];
rz(-gamma) q[1];
cx q[0], q[1];
// U_B(beta)
rx(2 * beta) q;
result = measure q;
reset q;Start the QAOA layer from |00>
h q;Prepare all four candidates uniformly
cx; rz(-gamma); cx;Cost matching the convention U_C=e^{-iγC}
rx(2 * beta) q;Mixer; the RX angle is 2β
gamma=pi/2, beta=pi/8In this example, 01 and 10 each become 50%
measureReturn candidate bit strings to the classical side

17.5 Angles are updated outside the circuit

Fig. 23How quantum and classical processing alternate in QAOA

Check your understanding

  1. What score results from substituting candidate 01 into C=x0+x1−2x0x1?

    Show answer: What score results from substituting candidate 01 into C=x0+x1−2x0x1?

    0+1−2×0×1=1.

  2. With U_C=e^{-iγC}, why is the RZ angle −γ?

    Show answer: With U_C=e^{-iγC}, why is the RZ angle −γ?

    Because C=(I−ZZ)/2, Cost without the common phase is e^{+iγZZ/2}. CX-RZ(θ)-CX produces e^{-iθZZ/2}, so θ=−γ.

  3. What is the ideal measurement distribution for γ=π/2 and β=π/8?

    Show answer: What is the ideal measurement distribution for γ=π/2 and β=π/8?

    01 is 50%, 10 is 50%, and 00 and 11 are 0%.

  4. Where is the process that updates γ and β usually run?

    Show answer: Where is the process that updates γ and β usually run?

    In a classical optimizer outside the OpenQASM circuit.

CHAPTER 18

The pattern for OpenQASM 2→3 migration and debugging

Preserve meaning, then isolate source, logic, hardware, and noise in order

In this chapter, ‘correct’ has four layers: the text can be read, the quantum-state calculation matches the intention, the circuit fits the device constraints, and the hardware result is within an acceptable range. If an earlier layer has not passed, checking a later layer cannot reveal the real cause.

18.1 Read the same Bell circuit through two versions

Migration is not a global word replacement. First determine the state and ideal distribution produced by the old code, then express the same meaning with the new declarations and measurement syntax. We use the same Bell circuit, where H and CX produce 00 and 11.

Move only the spelling while preserving meaning

Both sides create the same Bell state and the same 00/11 distribution. Match only the lines whose spelling changes.

Before · OpenQASM 2.0

Complete Bell program

OpenQASM 2.0program
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
h q[0];
cx q[0], q[1];
measure q -> c;
qreg q[2];Declare a quantum register containing two qubits
creg c[2];Declare a classical register containing two bits
h; cx;The logic that creates the Bell state stays the same in version 3
measure q -> c;Store measurement results in c with an arrow

After · OpenQASM 3.1

Complete Bell program

OpenQASM 3.1program
OPENQASM 3.1;
include "stdgates.inc";
output bit[2] result;
qubit[2] q;
reset q;
h q[0];
cx q[0], q[1];
result = measure q;
qubit[2] q;Declare the qubit type instead of qreg
output bit[2] result;Explicitly declare the returned classical value as bits
reset q;Declarations start undefined, so explicitly prepare the intended |00> state
h; cx;Do not change the Bell state the circuit is meant to create
result = measure q;Store measurement results with an assignment expression

Migrate the Bell circuit one meaning at a time

At each stage, separate the grammar that changes from the circuit meaning that must not change.

  1. STEP 1Change the version and standard library

    Move from version 2.0’s qelib1.inc to version 3.1’s stdgates.inc. Confirm that the target version defines the h and cx gates you need.

    OPENQASM 3.1;include "stdgates.inc";
  2. STEP 2Declare the types and make the starting state explicit

    Move qreg to qubit and creg to bit. In 3.1, a bit value to be returned can be marked as output. A newly declared qubit has undefined state, so reset q; explicitly preserves the Bell circuit's intended |00> start.

    output bit[2] result;qubit[2] q;reset q;
  3. STEP 3Preserve the logic of H and CX

    The h q[0]; and cx q[0],q[1]; that create the Bell state stay the same. It is essential not to swap the control and target.

    Ideal state
    (|00>+|11>)/√2
    h q[0];cx q[0], q[1];
  4. STEP 4Move measurement to an assignment expression

    Change measure q -> c; to result = measure q;. Confirm that the width-two destination matches the two measured qubits.

    Ideal distribution
    00:50%, 11:50%
    result = measure q;
Common migration mappings
OpenQASM 2OpenQASM 3.1Meaning to verify
OPENQASM 2.0;OPENQASM 3.1;Target version
include "qelib1.inc";include "stdgates.inc";Source of gate definitions
qreg q[2];qubit[2] q; + reset q;Two quantum items and an explicit |00> start
creg c[2];bit[2] c;Two items of classical data
measure q -> c;c = measure q;Store measurement results
if (c==1) x q[0];if (c == 1) { x q[0]; }Branch on a classical condition

18.2 Separate errors into three layers

Fig. 24Four questions that classify a failure from top to bottom

18.3 Diagnose three failures in the same order

Narrow a symptom to one layer at a time

Fix one representative source/front-end, logic, and hardware-constraint failure.

  1. CASE ASource: the qubit declaration is missing ;

    The parser stops near the qubit[2] q line. Check the end of the failing line first and add the semicolon. This is not yet the stage for suspecting state calculations or hardware.

    Classification
    Source/front end
    qubit[2] qh q[0];
  2. CASE BLogic: CX control and target are reversed

    If h q[0] is followed by cx q[1],q[0], control q[1] is 0, so CX does nothing. The results are 00 and 10 rather than the intended 00 and 11. Fix it to cx q[0],q[1].

    Classification
    Logic error
    h q[0];// Wrong: control and target are reversedcx q[1], q[0];
  3. CASE CHardware constraint: physical qubits 0 and 2 are not directly connected

    The ideal simulator is correct, but the hardware rejects the circuit. If the ISA connects only 0–1–2, a direct CX between 0 and 2 is unavailable. Transpile for the target hardware and inspect the routing, including any SWAPs.

    Classification
    Hardware-constraint error
SymptomLayer to inspect firstMinimal test
parse errorVersion, ;, brackets, declarationsTrim to the failing line, then restore one line at a time
undefined gateinclude and standard gate nameParse a one-gate minimum
Reversed result or wrong candidateControl/target, gate order, bit orderA circuit with X on only one qubit
Always 0 when 50:50 was expectedH, measurement basis, state cardUpdate the state after each gate
Only hardware rejects itISA, connectivity, supported featuresTranspile for the target hardware
A few nonideal resultsShots and noiseCompare with an ideal simulator

18.4 A fixed debugging procedure

  1. 1Write the expected input, state card after every gate, and ideal measurement distribution first.
  2. 2Minimize the code, then pass parsing and static validation for the target version.
  3. 3Check whether an ideal simulator matches the ideal distribution.
  4. 4Place X on only one qubit and verify the display order of the result string’s bits.
  5. 5Transpile for the target hardware and inspect placement, added SWAPs, basis gates, and depth.
  6. 6Finally compare hardware results with the ideal distribution and investigate finite shots and noise.

18.5 The mastery project and passing criteria

ProjectRequired deliverables
A Quantum coin tossInput angle theta, ideal RY probability, shot fluctuation, complete QASM
B Bell correlation testerFour-component state, Z/X-basis predictions, ideal distribution, complete QASM
C Two-bit Groverf(x) table, changeable Oracle, complete amplitude calculation, complete QASM
D Two-variable QAOAScore table, QUBO/Ising, Cost/Mixer, outside angle update
E Migration and debuggingQASM 2→3 diff, failures in three layers, diagnosis record, corrected version
Whichever project you choose, meet all five criteria
CriterionNot yetPassMastery
PredictionOnly the result after executionWrite the ideal distribution before executionJustify the state after every gate
CodeA fragment or code that does not parseComplete QASM that parses in the target versionConnect every line to a state change
VerificationHardware results onlyCompare with an ideal simulatorTest bit order, shots, and noise separately
BoundaryDescribe all processing as QASMDistinguish inside and outside the circuitDiagram ownership of inputs, shots, optimization, and transpilation
ExplanationList terminology onlyExplain cause and effect with numbers and diagramsApply the same method to another input or condition

Check your understanding

  1. How can OpenQASM 2’s measure q -> c; be written in 3.1?

    Show answer: How can OpenQASM 2’s measure q -> c; be written in 3.1?

    As the assignment expression c = measure q;.

  2. A Bell circuit parses but produces only 00 and 10. Which error should you suspect first?

    Show answer: A Bell circuit parses but produces only 00 and 10. Which error should you suspect first?

    A logic error. Check which qubit receives H and the control and target of CX.

  3. The ideal simulator is correct, but hardware rejects a CX. What should you inspect next?

    Show answer: The ideal simulator is correct, but hardware rejects a CX. What should you inspect next?

    Inspect the target device’s ISA, especially physical-qubit connectivity and basis gates, and transpile for that device.

  4. Besides code, what must a mastery deliverable include at minimum?

    Show answer: Besides code, what must a mastery deliverable include at minimum?

    A verification record explaining the pre-execution prediction, state changes, ideal distribution, out-of-circuit processing, and differences between ideal and hardware results.

Appendix A

Minimal glossary

TermMeaning in this book
qubita quantum information unit whose pre-measurement state is recorded with amplitudes and that returns 0/1 on a standard measurement
amplitudea number before probability is computed; its absolute value squared is the probability
Ha gate that changes [a,b] to [(a+b)/√2,(a−b)/√2]
Za gate that changes [a,b] to [a,−b]
interferenceseveral amplitudes entering the addition/subtraction of the same output amplitude, changing its magnitude
Z-basisa standard measurement that distinguishes |0> and |1>
X-basisa measurement that distinguishes |+> and |->; standard measurement after H
CXa two-qubit gate that applies X to the target on the component where the control is 1
entanglementa state whose whole cannot be written as independent per-qubit states
shotone independent run of the whole quantum program from preparation to measurement
Oraclea component that judges with a circuit whether a candidate meets a condition and adds a phase mark
QUBOan optimization problem written as linear and quadratic expressions of 0/1 variables
QAOAa gate-model algorithm using Cost and Mixer, updating angles on the classical side

Appendix B

Gate quick reference

GateOpenQASMThe role to check first
Xx q;swap |0> and |1>
Hh q;remake amplitudes from sum and difference
Zz q;flip the sign of the 1-side amplitude
CXcx a,b;flip b with X on the component where a is 1
RYry(theta) q;move 0/1 likelihoods with real amplitudes
RXrx(theta) q;move likelihoods and add complex phase to the 1 side
RZrz(theta) q;move relative phase while preserving Z-basis probabilities
RZZcx; rz(theta); cx;separate phase by whether two qubits match or differ
SWAPswap a,b;swap the states of two qubits

Appendix C

Math notes

  • •1/√2 ≈ 0.707, (1/√2)² = 1/2.
  • •Probabilities sum to 1. For a one-qubit real amplitude, a²+b²=1.
  • •A negative amplitude is not a negative probability. Probability is the amplitude's absolute value squared.
  • •H[a,b]=[(a+b)/√2,(a−b)/√2].
  • •Grover diffusion, learning calculation: new amplitude = 2 × mean of all amplitudes − old amplitude.

Appendix D

Learning checklist

  • Can compute X/H/Z with the state card
  • Can write the 0-side and 1-side add/subtract in H-Z-H
  • Can distinguish the Z basis and X basis as circuits
  • Can answer the four CX inputs from the rule, not from memory
  • Can follow the 4-component state of the Bell circuit
  • Can write OpenQASM declarations, gates, and measurement
  • Can distinguish mid-circuit measurement from shots
  • Can explain why an Oracle is not an answer generator
  • Can fully compute the amplitudes of 2-bit Grover
  • Can distinguish QUBO from a QAOA circuit
  • Can distinguish a logical circuit from a hardware-targeted circuit
  • Can explain what RX, RY, RZ, and RZZ change and what they leave unchanged immediately

Appendix E

Official resources

Bring us the problem you are weighing up.

Whether quantum and AI are worth trying on it at all, and what would differ from the method you use now. An undecided question is the right place to start.

We begin by setting out the problem, its constraints and what would count as a good answer.

And for every challenger who wants to show their ability through practice.