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 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.

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

0.4 OpenQASM writes the same procedure as text

openqasm
OPENQASM 3.1;
include "stdgates.inc";
qubit q;
bit result;
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
result = measure q;Measures q and puts 0 or 1 into result

0.5 The first experiment

What to checkDetail
Startq usually begins in |0>
OperationMeasure without doing anything
ResultIdeally always 0
ReasonBecause at the start it reads as 0

Check your understanding

  1. 1Which way does time flow in a circuit diagram?
  2. 2How many answers does one standard measurement give?
  3. 3Are a qubit and a bit the same?

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.

openqasm
OPENQASM 3.1;
include "stdgates.inc";
qubit q;
bit result;
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. 1What does |1> become after X?
  2. 2What appears if you apply X twice to |0> and measure?
  3. 3What does the q in x q; represent?

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. 11000 shots means doing what 1000 times?
  2. 2Where are shots usually specified relative to OpenQASM?
  3. 3What happens with an ideal X → measure over 1000 shots?

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.

[a, b]state card
0-side: a → a²
P(0) = a²
[a, b]state card
1-side: b → b²
P(1) = b²
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. 1What is the measurement result of the state card [1,0]?
  2. 2What is the square of 1/√2?
  3. 3Does the amplitude −1/√2 mean a negative probability?

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.

[a, b]input
(a+b)/√2new 0-side
[a, b]input
(a−b)/√2new 1-side
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.

1
0
01
|0>
0
1
01
|1>
1/2
1/2
01
H|0>

Probability = amplitude squared

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
openqasm
OPENQASM 3.1;
include "stdgates.inc";
qubit q;
bit result;
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. 1What is the state card of H|0>?
  2. 2Why is the 1-side amplitude of H|1> negative?
  3. 3What happens if you apply H twice?

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
Start[1, 0]|0>
First H[1/√2, 1/√2]|+>
Z[1/√2, −1/√2]|->
Last H[0, 1]|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.

openqasm
OPENQASM 3.1;
include "stdgates.inc";
qubit q;
bit result;
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. 1How does Z change the state card [a,b]?
  2. 2Write the addition that makes the 0-side amplitude 0 in H-Z-H.
  3. 3What is interference in this book?

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>.

Z-basisX-basisH
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
openqasm
// 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. 1What does a standard measure distinguish?
  2. 2What do you place before measuring in the X basis?
  3. 3What appears when you measure |+> in the X basis?

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.

q[0]q[1]X
Fig. 7Apply X to q[0] only; whether the result reads 10 or 01 confirms the bit ordering.
openqasm
OPENQASM 3.1;
include "stdgates.inc";
qubit[2] q;
bit[2] c;
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. 1How many measurement candidates does a two-qubit system have?
  2. 2Write the 4-component state card of |01>.
  3. 3What is the minimal test to confirm the result-string order?

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'

q[0] controlq[1] 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].

openqasm
OPENQASM 3.1;
include "stdgates.inc";
qubit[2] q;
bit[2] c;
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. 1What is the first argument of CX?
  2. 2What do you get by applying cx q[0],q[1] to input 11?
  3. 3What do you get by applying cx q[1],q[0] to input 10?

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
q[0]q[1]H
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.

50%
50%
01
q[0] alone
50%
50%
01
q[1] alone
50%
50%
00011011
the two together
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.

openqasm
OPENQASM 3.1;
include "stdgates.inc";
qubit[2] q;
bit[2] c;
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. 1Which bit strings never appear from this Bell circuit?
  2. 2What are the 0/1 ratios of each qubit alone?
  3. 3Can you communicate instantly with entanglement alone?

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
// 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

openqasm
OPENQASM 3.1;
include "stdgates.inc";
qubit[2] q;
bit[2] c;
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
Lines 5–6Prepare a Bell state
Line 7Measure both qubits

Check your understanding

  1. 1What is the maximum valid index for qubit[4] q;?
  2. 2What is the main role of the semicolon?
  3. 3What does include "stdgates.inc"; enable?

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
reset q[0];

11.3 Check a classical bit with if

openqasm
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. 1May you compare a qubit directly as q[0]==1 in an if?
  2. 2What is the ideal state after reset?
  3. 3What is the difference between a dynamic circuit and 1000 shots?

CHAPTER 12

Types, inputs, and loops

Placing classical computation around quantum instructions

12.1 A type decides how a value is used

TypeExampleUse
bit / bit[n]bit[3] c;measurement results
boolbool done=false;true/false
int / uintuint[8] count;integers
floatfloat[64] score;decimals
angleangle theta;a periodic angle
durationduration t=100ns;time

12.2 input receives a value from outside the circuit

openqasm
input angle theta;
output bit result;
qubit q;
ry(theta) q;
result = measure q;

12.3 for is a repetition with a fixed count

openqasm
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.

12.4 while repeats while the condition is true

openqasm
bit success = 0;
while (success == 0) {
  reset q;
  h q;
  success = measure q;
}

Check your understanding

  1. 1Where does theta in input angle theta; come from?
  2. 2How many times does for int i in [0:3] run?
  3. 3Are while and shots the same?

CHAPTER 13

Angled gates and modularizing circuits

Widen phase into angles, and use gate, modifiers, and def appropriately

13.1 + and − are phases of 0° and 180°

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°.

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

13.3 The roles of RX, RZ, RZZ

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
RZZrzz(theta) a,b;phase depending on the two-qubit relation

13.4 gate names a sequence of quantum operations

openqasm
gate make_bell a, b {
  h a;
  cx a, b;
}
qubit[2] q;
make_bell q[0], q[1];

13.5 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.6 def is a general subroutine

openqasm
def parity(bit[4] x) -> bit {
  bit p = 0;
  for int i in [0:3] {
    p ^= x[i];
  }
  return p;
}
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. 1For modularizing a Bell circuit, is gate or def more natural?
  2. 2What is inv @ h q; the same as?
  3. 3What do you use for classical processing that returns a value?

CHAPTER 14

Running a logical circuit on real hardware

Separate barrier, delay, pulse, noise, and transpilation

14.1 The circuit you wrote does not always go to the device as-is

We write logical instructions such as H and CX. Real hardware has only a limited set of physical qubits, connections, and native gates. So before sending, we convert to a device-specific instruction sequence that does the same job.

StageExampleWhat to check
Logical circuitH, CXIs it the intended state change?
Placementlogical q[0] → physical qubit 7Did you pick good qubits?
Routingadd SWAPAre connectivity constraints met?
Native decompositionCX → device-specific instructionsWill the device accept it?
Executionplay pulsesnoise and timing

14.2 barrier is not a gate that changes the state

openqasm
h q[0];
barrier q;
cx q[0], q[1];

14.3 delay makes the wait time explicit

openqasm
delay[100ns] q[0];

14.4 pulse is a physical signal

14.5 Separate an ideal 50:50 from a dirty result

H|0> is ideally 0/1 at 50:50. Even if it becomes 48:52 on real hardware, it may be fluctuation from the finite 1000 shots. On the other hand, if a Bell circuit continually produces 01 or 10 that should not appear, suspect gate or readout errors.

Check your understanding

  1. 1Does barrier flip the ideal state?
  2. 2What does transpilation convert to?
  3. 3Does 48:52 for H immediately mean a fault?

CHAPTER 15

Separating algorithm, circuit, and Oracle

Untangling why Grover looks like it 'knows the answer'

15.1 An algorithm is the blueprint; a circuit is the instruction list

LayerGrover exampleRole
Problemfind one satisfying a condition among 4 candidateswhat to solve
Algorithmequalize → mark → amplify → measurehow to solve
Quantum circuitH, Oracle circuit, diffusion circuitan executable gate sequence
OpenQASMh q; cx ...;describe the circuit as text
Problemwhat to solve
Algorithmhow to solve
Quantum circuitexecutable gate sequence
OpenQASMthe circuit as text
Fig. 11The layers from problem to quantum hardware. OpenQASM is not the algorithm itself.

15.2 An Oracle is a judge, not an answer generator

For example, to build an Oracle where only candidate 10 is correct, you turn the check rule 'true if the input is 10' into a circuit. This does not read out candidate 10 from the start; it checks, by the same rule, whether each input candidate matches the condition. Classical search also needs the same check every time it tries a candidate.

+
+
+
+
00011011
Before Oracle
+
+
+
00011011
After Oracle

The vertical axis is amplitude (signed). Since probability is amplitude squared, every candidate is still 25% here.

Fig. 12The Oracle flips the sign of only candidate 10's amplitude. The four candidates still measure at 25% each right after.

15.3 Distinguish 'optimal' from 'matches the condition'

A standard Grover Oracle judges whether a candidate meets a specified condition. It does not automatically know the shortest route of a VRP. To use it for optimization, you need additional classical steps, such as judging whether a value is below a threshold and updating that threshold.

Check your understanding

  1. 1Are an algorithm and a quantum circuit the same?
  2. 2What does an Oracle do to candidates?
  3. 3Does a VRP Oracle automatically know the shortest route?

CHAPTER 16

Computing Grover fully with four candidates

Why just marking makes the correct answer easier to measure

16.1 Take the candidates as 00, 01, 10, 11

Applying H to two qubits makes all four candidate amplitudes 1/2. Each probability is (1/2)² = 1/4, so measuring gives 25% for every candidate.

16.2 The Oracle flips the sign of 10 only

Let candidate 10 match the condition. After the Oracle the state card is [1/2,1/2,−1/2,1/2]. The probabilities are still all 1/4, so measuring at this point still succeeds only 25% of the time.

16.3 Do the inversion about the mean with numbers

The mean of the four amplitudes is (1/2 + 1/2 − 1/2 + 1/2)/4 = 1/4. Compute each new amplitude as '2 × mean − old amplitude'.

CandidateOld amplitude2 × mean − oldNew amplitude
001/21/2−1/20
011/21/2−1/20
10 correct−1/21/2−(−1/2)1
111/21/2−1/20
00011011
Equalized
00011011
After Oracle
1
00011011
After diffusion

The vertical axis is amplitude (signed).

Fig. 13Grover's amplitude changes: compare equalization, the Oracle sign flip, and the concentration onto 10 after diffusion.

16.4 This is the concrete content of interference

The amplitude calculations for candidates 00, 01, 11 became 0, while candidate 10's became 1. 'Reinforcing the correct answer' means that, through a circuit that adds and subtracts amplitudes, the new amplitudes of non-answers became 0 and the answer's became 1.

16.5 In general, choose the number of iterations

When the number of answers is small relative to the candidate count N, repeat the Oracle and diffusion on the order of about √N times. Repeating too much lowers the answer amplitude again, so running infinitely is not the goal.

Hequalize
Oraclesign flip
Diffusionspread
Measurebit string
Fig. 14Grover's four stages viewed as circuit blocks.Diff is short for diffusion. It is the part that executes as a circuit the 'inversion about the mean' computed in this chapter.

Check your understanding

  1. 1What is the probability of 10 right after the Oracle?
  2. 2What is the mean of the four amplitudes?
  3. 3What is the state card after diffusion?

CHAPTER 17

From QUBO to a QAOA circuit

Don't confuse formulating the problem with the circuit that solves it

17.1 Optimization scores each candidate

Consider a simple MaxCut that splits two people x0, x1 into different groups. xi=0 means group A, 1 means B. If the two differ, score 1; if the same, 0.

x0x1same/differentscore C
00same0
01different1
10different1
11same0

17.2 QUBO translates the problem into a 0/1 quadratic

This score can be written C = x0 + x1 − 2·x0·x1. It gives 0 for 00, 1 for 01, 1 for 10, 0 for 11. You can confirm this by substituting the table's four rows.

17.3 Map QUBO to the Ising representation

You can replace a QUBO variable x∈{0,1} with an Ising variable z∈{+1,−1} via x=(1−z)/2. The two-person MaxCut score becomes C=(1−z0·z1)/2. In a quantum circuit, the role of z is replaced by a Z operator, creating a phase change according to each candidate's cost.

17.4 QAOA evaluates the QUBO-derived cost with a circuit

Stagequantum/classicalRole
Initialize with Hquantumamplitude on all candidates
Cost(γ)quantumchange the amplitude angle by each candidate's cost
Mixer(β)quantummix amplitudes between candidates, changing probabilities
Measurequantum → classicalobtain a candidate bit string
Tally costclassicalcompute the mean score of candidates
Update γ,βclassicalpass angles to the next circuit run

Quantum side (the core expressed in OpenQASM)

Hinitialize
Cost(γ)phase marking
Mixer(β)redistribute
Measurebit string
samples

Classical side (usually outside OpenQASM)

QUBOscore formula
Tallymean cost
Optimizeupdate γ,β
next γ,β
re-run
Pass the updated angles to the next circuit run
Fig. 15QAOA's quantum and classical sides. OpenQASM mainly represents one quantum circuit; angle updates happen outside.QUBO is the problem formula, OpenQASM is the quantum circuit, angle update is classical processing. Read the three separately.

17.5 A two-variable, one-layer OpenQASM skeleton

openqasm
OPENQASM 3.1;
include "stdgates.inc";
input angle gamma;
input angle beta;
output bit[2] result;
qubit[2] q;
h q;
rzz(2 * gamma) q[0], q[1];
rx(2 * beta) q;
result = measure q;
h q;Prepare 00,01,10,11 uniformly
rzz(...)Part of the Cost matching the x0x1 relation
rx(...)The Mixer redistributes amplitudes
measureRead a candidate
gamma,betaUpdated by the classical optimizer outside the circuit
Hinitialize
CostRZZ(γ)
MixerRX(β)
Measure
Fig. 16One QAOA layer as circuit blocks. The Cost's γ and the Mixer's β are passed from outside.

Check your understanding

  1. 1Is QUBO a quantum circuit?
  2. 2Where does QAOA's angle update usually happen?
  3. 3State the roles of Cost and Mixer in one sentence each.

CHAPTER 18

Migrating OpenQASM 2 to 3, and end-to-end debugging

Inspect correct code, correct logic, and hardware fit separately

18.1 Compare the same Bell circuit

OpenQASM 2OpenQASM 3
OPENQASM 2.0;OPENQASM 3.1;
include "qelib1.inc";include "stdgates.inc";
qreg q[2];qubit[2] q;
creg c[2];bit[2] c;
measure q -> c;c = measure q;
if (c==1) x q[0];if (c == 1) { x q[0]; }

18.2 Split errors into three layers

SymptomCheck firstMinimal fix
parse errorversion, ;, brackets, spellingtrim to the failing line, then add back one line at a time
undefined gateinclude and letter casecheck stdgates.inc and gate names
result is reversedcontrol/target, bit orderminimal test with X on one side only
always 0 when 50:50 expectedis there an H, measurement basisupdate the state card each line
hardware rejectssupported features and ISAtranspile to the target device
a few wrong resultsshots and noisecompare with an ideal simulator

18.3 A fixed debugging procedure

  1. 1Write the expected input and the ideal measurement distribution on paper.
  2. 2Minimize the circuit and update the state card one gate at a time.
  3. 3Check only the syntax with a parser.
  4. 4Check the count distribution with an ideal simulator.
  5. 5Confirm the bit display order with an X on one side.
  6. 6Transpile to the target device and check added gates and depth.
  7. 7Compare the real-hardware result with the ideal distribution and isolate noise.
Ideal statecompute the state card
Syntaxcheck with a parser
Simulatorideal count distribution
Bit orderone-side X test
Hardware limitstranspile
Noisegap from real hardware
Fig. 17When results look wrong, narrow the cause in order: ideal state, syntax, simulator, bit order, hardware constraints, noise.

18.4 Capstone projects

ProjectRequired deliverable
A Quantum coin tossvary RY with input angle theta; explain ideal probability and shot fluctuation
B Bell correlation testerprepare 4 Bell states; compare correlation in Z/X bases
C 2-bit Grovera circuit with a changeable Oracle condition; the full 4-component amplitude calculation
D 2-variable QAOAseparate the QUBO table, Cost/Mixer circuits, and the outer angle update
E Migration & debuggingmigrate QASM 2 code to 3 and fix the three kinds of faults

Check your understanding

  1. 1What is the difference between a syntax error and a logic error?
  2. 2May you assume a hardware rejection is a logic mistake?
  3. 3Beyond code, what is needed for the mastery judgment?

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
RX/RY/RZrx(theta) q;an angled rotation about the given axis
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

Appendix E

Official resources

Start with one challenge.

Define the capabilities you need. Validate practical ability. Choose the right people and teams.

QVillager connects quantum work with proven ability, and accumulates the evidence those decisions can reuse.

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