Lecture 6 - Searching and Cryptography
Chapter map
- Chapter 06: Searching and Cryptography (Prachya Boonkwan, SIIT, version Jan 15, 2026). Taught Oct 27 and Nov 3.
- 1. Grover's Search Algorithm: unstructured search in by sign-flipping and amplitude amplification
- 2. Quantum Fourier Transform: time series → frequency domain in . InvQFT goes back.
- 3. Quantum Phase Estimation (QPE) {Exam Q5}: read the global phase of a unitary by "rotating the clock" many times and decoding with InvQFT. Slides 28–33.
- 4. Shor's Algorithm {Exam Q5}: crypto background (GCD, coprime, totient, Fermat–Euler, RSA), then the hybrid factorization that uses QPE to find the order , then continued fractions. Slides 40–41, 44, 47–50, 53–56.
- 5. Simon's Algorithm: tests whether a hash function is one-to-one
- 6. Conclusion
- Final exam: only Q5 [Shor's Algorithm] comes from this chapter. Its slides are 28–33, 40–41, 44, 47–50 and 53–56. See Final - Instructor Hints.
- Exam style: "why" questions, reasons and design, "no math derivation".
Related
- Lecture 1 - Complex Algebra: = rotation on the unit circle. Used everywhere here.
- Lecture 1 - Complex Algebra: QPE reads the eigenvalue of a unitary.
- Lecture 1 - Complex Algebra: Grover's diffusion operator is a Householder reflection.
- Lecture 5 - Leveraging Superposition, Entanglement, and Error Correction: phase kickback (used inside QPE and Simon) and the Deutsch algorithm.
- Lecture 7 - System Dynamics, Simulation, and Polynomial Functions: Hamiltonian and Trotterization speed up in QPE.
1. Grover's Search Algorithm
Information Retrieval
- Information retrieval: the task of identifying and retrieving information sources relevant to an information need
- Indexing: the keywords (the key) are extracted from each document in the dataset
- Search: the user's query is matched against each document's key sequentially
- If they match, the solution (the correct output value) is retrieved for the user
- Limitation: the time complexity of unstructured search is
- Figure 1: Query → compared against the Keys column → "Match & retrieve" → Values
🎙️ In class (Oct 27, 10:49): "sounds okay until you realize you've got billions of documents". Quantum search will not reach , "but we can achieve much better".
💡 Analogy: Finding one friend's phone number in a paper phone book that is not sorted. You have to read the entries one by one.
Quantum Search Algorithm
- Quantum search algorithm: a quantum method for unstructured search. The solution is retrieved with the highest probability in time
- Motivation: assign a probability distribution over the entire search space for finding the desired solution w.r.t. the query. Then gradually amplify the probability of the solution via the oracle function
- Oracle function:
- Construct the oracle operator by sign-flipping the solution :
📝 Instructor's annotation: wrote "(non-solution: +1)" next to the term and "(solution: −1)" next to the term. Below: for the solution, and for a non-solution. (His letters are swapped relative to the slide. The meaning is: solution → minus sign, non-solution → unchanged.)
🎙️ In class (Oct 27, 21:49): "The oracle operator is hidden. You never know the solution on the inside. We just know its behaviour: every time it matches the solution, it flips the sign."
❓ Why? A sign flip does not change any measurement probability (). It "marks" the solution invisibly, and the next step (the diffusion) turns that mark into a bigger amplitude.
Overview of Grover's Search Algorithm

- Figure 2: four steps on an 8-item search space (000…111). The solution is .
- Setup: every item has amplitude . The mean vector is drawn as a red arrow.
- Oracle: the solution is temporarily sign-flipped, so goes to
- Grover: recompute the mean vector, which shifts from to
- Grover: amplify the probability amplitudes around the new mean vector. The solution's bar becomes tall.
- Then loop back to step 2
📝 Instructor's annotation: beside step 1 he drew a small 3-D sketch: "mean vector is perpendicular to the solution plane". Under step 4: "(rotate the solution plane by holding the mean vector)".
🎙️ In class (Oct 27, 16:50–19:35): In the quantum world, the mean is not a line but a vector, perpendicular to the distribution. Flipping the solution's sign shifts the mean towards the solution. You readjust every candidate around the new mean and repeat "until you've got the mean vector on top of the solution". "Simple overview, but mathematically it's difficult."
💡 Analogy: "Inversion about the mean". Everyone in class scores about 50. The teacher secretly makes the one target student −50, so the class average drops a little. Then every score is reflected around the new average. Normal students barely move, but the target jumps far above everyone. Repeat a few times.
Sign-Flipping and Amplitude Amplification

- Step 1: let and compute the mean vector
- Step 2: temporarily sign-flip the solution:
- Step 3: recompute the mean vector:
- Step 4: amplify the probability amplitudes:
- The diffusion operator is a Householder reflection through the axis :
- Figure 3: geometric interpretation. The vector is the sum of non-solutions. The angle always increases by .
📝 Instructor's annotation: labelled the axes "solution " and ": the sum of non-solutions". Labelled ": old mean vector" and ": new mean vector". Wrote "sometimes it's called 'sling shot'".
🎙️ In class (Oct 27, 24:24–29:03): "The idea is called slingshot." Reflection 1 (the oracle) flips the mean vector across ("pull the shot"). Reflection 2 (the diffusion) flips it across the old mean vector ("release the shot"). "Pull, release, pull, release". Each round brings the mean vector closer to the solution.
❓ Why does it rotate? Two reflections in a row = a rotation by twice the angle between the mirrors. The start vector makes angle with , so each pull+release turns it by exactly towards .
Optimal Number of Iterations

- Each iteration recomputes the mean vector from by rotating by a constant angle
- We want to rotate for iterations so that we approximate the solution , which is perpendicular to the reflection basis :
- Consider a uniform superposition:
- Since is a unit vector of the form :
- Therefore the optimal number of iterations is
- Going beyond is called overshooting
📝 Instructor's annotation: drew vs with rotating towards by : "rotate for times". Under the small-angle step: "substitute to ".
🎙️ In class (Oct 27, 31:42): the floor is used because you must not overshoot: "go beyond the solution, that's overshoot. We need to keep it within the limit."
🎙️ In class (Oct 27, 33:45–37:15): "All physicists got stuck at this point" (the term), until they noticed that is millions, so is tiny and .
🎙️ In class (Oct 27, 37:28): exam style: "no math derivation at all. But I'm going to ask, e.g., how could we come up with the number of iterations?"
❓ Why ? , so the total angle from to the solution is 90°. Start at , add per iteration, and stop when you reach 90°.
❓ Why is it ? iterations, each with one oracle call. Classical search needs .
💡 Analogy: Turning a dial towards 12 o'clock in fixed clicks. Too few clicks and you haven't arrived. Too many and you pass it (overshoot), and the probability of the answer goes down again.
Grover's Search Algorithm

- Figure 4: wires start in , then H on each wire. A dashed box "for to int()" contains → H → → H. Then measure all wires.
- PennyLane:
- Steps 1 and 2 are done by
qml.FlipSign(statevec, wires=...) - Steps 3 and 4 () are done by
qml.templates.GroverOperator(wires=...)
- Steps 1 and 2 are done by
Grover's Search Algorithm (Actual Implementation)

- Figure 5: the Grover operator replaces
- Initial H on all wires, then
- On every wire except the last: H, then a control dot, then H
- On the last wire: Z, then the multi-controlled NOT target (a Toffoli-like gate), then Z
- Then measure all wires
🎙️ In class (Oct 27, 40:36–41:27; 47:12): "This is my " (TOC joke: "show me your D"). is really hard to implement in practice, so the physicists replaced it with the Grover operator, "which works exactly the same". Mnemonic: "Hadamard and Z, Hadamard and Z, and Toffoli in the middle."
🎙️ In class (Oct 27, 42:33): Lov Grover: "although his name sounds European, he's actually Indian."
Grover's Search Algorithm in PennyLane
soln = np.array([1,1,0,1]) # Solution: 1101
no_qubits = len(soln)
wires = range(no_qubits)
dev = qml.device('default.qubit', wires=wires)
def oracle(): # Treat it as a black box
qml.FlipSign(soln, wires=wires)
def uniform_superposition(wires):
for i in wires:
qml.Hadamard(wires=i)
@qml.qnode(device=dev, shots=1000)
def grover_search(): # Note that the solution is always hidden in the oracle
no_iters = int(np.pi / 4 * np.sqrt(2 ** no_qubits))
uniform_superposition(wires)
for i in range(no_iters):
oracle()
qml.templates.GroverOperator(wires=wires) # Diffusion operator
return qml.counts(wires=range(no_qubits))
grover_search() # Expected result: {'1101': 1000}Grover's Search Algorithm for Multiple Solutions
- Incorporate multiple solutions and non-solutions , where is the size of the search space:
- The optimal number of iterations comes from:
- Since : for small
- The optimal number of iterations is
📝 Instructor's annotation: under : "sum of solutions". Under : "sum of non-solutions".
🎙️ In class (Oct 27, 46:22): with more solutions, fewer iterations are needed. It is still .
Grover's Search Algorithm for Multiple Solutions in PennyLane
solns = np.array([ [1,1,0,1], [0,1,0,1] ]) # Solutions: 1101 and 0101
[no_solns, no_qubits] = solns.shape
wires = range(no_qubits)
dev = qml.device('default.qubit', wires=wires)
def oracle():
for soln in solns: # We sign-flip on each solution
qml.FlipSign(soln, wires=wires)
def uniform_superposition(wires):
for i in wires:
qml.Hadamard(wires=i)
@qml.qnode(device=dev, shots=1000)
def grover_search(): # Observe the change in the iteration number
no_iters = int(np.pi / 4 * np.sqrt(2 ** no_qubits / no_solns))
uniform_superposition(wires)
for i in range(no_iters):
oracle()
qml.templates.GroverOperator(wires=wires) # Diffusion operator
return qml.counts(wires=range(no_qubits))
grover_search() # Expected result: {'0101': 500, '1101': 500}Exercise 6.1: Grover's Search Algorithm
- Compute a unitary operator for the oracle functions whose solutions are:
- 01
- 010
- 110
- 1101
- 001 and 100
- 1010 and 0101
- 010, 011, and 110
- all binary representations that consist of one 1 and four 0's
- Answer the following questions:
9. Compute the optimal number of iterations for each of the oracle functions in Q.1–Q.8
10. Compute the rotation angle for each of the oracle functions in Q.1–Q.8
11. Implement PennyLane code for Grover's search algorithm using the oracle functions in Q.1–Q.8
12. Discuss what will happen when we overshoot in searching with Grover's search algorithm - Worked hint for Q.4: , , so and .
- Worked hint for Q.12: past the mean vector rotates past , so the solution's probability starts to decrease again.
2. Quantum Fourier Transform
Spectral Density

- A time series can be described in terms of its power distribution over the frequency components
- Assumption: a time series is a mixture of periodic sinusoid waves (seasonal patterns) of different frequencies :
- is its complex amplitude, and is its phase
- We want to transform a time series into spectra (squared amplitudes ) in the frequency domain
- Figure 6: spectral analysis of a time series (time domain → component waves → frequency domain → spectrum representation)
📝 Instructor's annotation: on the figure: "each composite wave has a complex amplitude ". The frequency-axis bars are marked "".
🎙️ In class (Oct 27, 49:18–53:18): a square wave is a combination of many waves. The time domain plots the combined wave against time. The frequency domain plots each component's amplitude (energy) against its frequency. The shaded strip is the spectrum ("the darker, the higher").
💡 Analogy: A smoothie (time domain) vs its recipe card (frequency domain): "70% mango, 20% banana, 10% milk". The Fourier transform reads the recipe out of the smoothie.
Classical Fourier Transform (definition)
- The Fourier transform of a time series is a function of that reflects how well aligns with the unit wave of frequency :
- is the cross-correlation operator:
- The frequency is usually a multiple of , which is one round of a circle in radians
- Figure 7: time-domain signal → frequency domain plot of at
❓ Why the conjugate? Correlation = inner product. Multiplying by the conjugate wave "un-rotates" the matching frequency so it adds up, while mismatched frequencies spin and cancel. (Same idea as phase synchronicity in Lecture 1.)
Classical Fourier Transform (via sampling)

- Figure 8: classical Fourier transform via sampling. Sampling frequencies take 2, 3, 4, 5 samples. Average the squared amplitudes to get one bar each → spectrum.
- Time complexity is due to the iterative steps
🎙️ In class (Oct 27, 55:52–58:35): "This is how we do it manually." For each sampling frequency, take the absolute value of each bar, square it, and average. AI students know this as "mean square error". This is exactly how speech recognition makes a spectrogram: one spectrum per 1 ms block. (He "deliberately put that in the Machine Learning final".)
🎙️ In class (Oct 27-02, 3:13–5:14): to get bars you take samples, , so .
Fast Fourier Transform (FFT)

- A popular classical algorithm for the discrete Fourier transform, based on recursion
- The length of the time series is of the form
- Base case ():
- Recursive case ():
- Figure 9: split the series into halves, FFT each, pair positions and that are apart, and combine. Time complexity , where is the length of .
📝 Instructor's annotation: braced as "recursive" and the two combine formulas as "combine the recursive results".
🎙️ In class (Oct 27-02, 9:43–10:23): "What is ? This is your cis, which means you are rotating it. Same amount of phase, one with +, one with −." "is the best we can do" classically.
💡 Analogy: Counting votes in a big election by splitting into provinces, counting each in parallel, then merging. Merging two halves is cheap if you rotate one half before adding.
Quantum Fourier Transform (QFT)
- The discrete Fourier transform converts an input time series into a frequency-domain vector :
- In quantum computing we treat a time series as a superposition of data points:
- Note that data points become qubits
- QFT as a state mapping:
- QFT operator:
📝 Instructor's annotation: drew a pie/unit circle with one slice of angle = . Highlighted "a superposition of data points".
🎙️ In class (Oct 27-02, 12:22): = "the -th root of unity, or let's say the -th slice of pie". Multiplying by it rotates by one slice.
🎙️ In class (Oct 27-02, 24:09–26:27): e.g. . Four elements need two qubits, elements need qubits. "If you have 1,000 elements, you need only 10 qubits."
🎙️ In class (Oct 27-02, 18:49): "Do you need to remember this matrix? No. Open book as always. Do you think I'm going to remember it? No."
💡 Analogy: A clock with ticks. Row of the matrix walks around the clock in steps of ticks.
Quantum Algorithm for Fourier Transform

- We imitate the root of unity by the dyadic rational phase gate :
- Conditional dyadic rational phase gate:
- the first qubit is the input/output, and the second qubit is the control
- Self-condition:
- Fourier block: maps to , and to , upon :
- Figure 10: Fourier block . Wire (with a triangle marking the target) passes through and outputs . Each () is controlled by .
📝 Instructor's annotation: under : "rotate by ", with a pie slice of angle . The triangle is labelled "target qubit of QFT". A brace on the control wires asks "what if all of them are superpositions?". Under the figure: "extract freq. domain from to a superposition in ".
🎙️ In class (Oct 27-02, 19:34–22:41): "A very scary name, dyadic rational phase gate. I just call it : keep , rotate by ." " means Hadamard."
⚠️ Note: literally . In the real circuit the first box on each target wire is a Hadamard (which also uses the phase on ). This is why the slide and the PennyLane code putqml.Hadamardthere. Exercise 6.2 Q7 asks about this.
Implementation of Quantum Fourier Transform

- For each qubit , map and
- Figure 11: QFT = a staircase of Fourier blocks
- Time complexity is
📝 Instructor's annotation: under : " = no. qubits → items!"
🎙️ In class (Oct 27-02, 26:33–28:11): block 1 has R-gates, block 2 has , and so on, so gates. "But here is the number of qubits, which accommodates items, so it's . See how small that is!"
Quantum Fourier Transform in PennyLane
- Quantum Fourier transform in PennyLane:
qml.QFT(wires=...) - His own implementation (shown for illustration):
def fourier_block(target, control_wires):
no_qubits = len(control_wires) + 1
qml.Hadamard(wires=target)
for wire in control_wires:
qml.ctrl(
qml.PhaseShift(
2 * np.pi / np.sqrt(no_qubits),
wires=target
)
)(control=wire)
def qft(wires):
for i in range(len(wires)):
fourier_block(wires[i], wires[i+1:])🎙️ In class (Oct 27-02, 28:19): "Do we really have to implement that ourselves? No. Don't do that. I did that myself and it took me ages. Just use this one command:
qml.QFT."
Inverse Quantum Fourier Transform (InvQFT)
- The inverse discrete Fourier transform converts a frequency-domain vector into a time series :
- InvQFT as a state mapping:
- InvQFT operator:
- Inverse property:
🎙️ In class (Oct 27-02, 30:16): "Look at the operator: it's minus, which means rotating backwards. Instead of counter-clockwise, you now rotate clockwise."
Quantum Algorithm for Inverse Fourier Transform

- The inverse of is , "because is a Hermitian matrix" (slide wording):
- The inverse of conditional :
- the first qubit is the input/output, and the second qubit is the control
- Inverse Fourier block: maps to and to , upon :
- Figure 12: inverse Fourier block. Wire passes through (mirror order), with the target triangle at the right end →
📝 Instructor's annotation: "rotate by ". The triangle is "target qubit of InvQFT". Text: "extract time domain from to a superposition in ".
⚠️ Note: the correct reason is that is unitary (so its inverse is its conjugate transpose ). A diagonal matrix with a complex entry is not Hermitian.
Implementation of Inverse Quantum Fourier Transform

- For each qubit , map and
- Figure 13: InvQFT () = the QFT staircase mirrored: first (bottom), up to last (top). Also .
🎙️ In class (Oct 27-02, 31:42): "QFT starts from the big block and gradually reduces the size. The inverse starts from the small one and gets bigger and bigger."
Inverse Quantum Fourier Transform in PennyLane
- Inverse quantum Fourier transform:
qml.adjoint(qml.QFT)(wires=...)
def inverse_fourier_block(target, control_wires):
no_qubits = len(control_wires) + 1
qml.Hadamard(wires=target)
for wire in control_wires:
qml.ctrl(
qml.PhaseShift(
- 2 * np.pi / np.sqrt(no_qubits),
wires=target
)
)(control=wire)
def invqft(wires):
for i in range(len(wires) - 1, -1, -1):
inverse_fourier_block(wires[i], wires[i+1:])🎙️ In class (Oct 27-02, 33:30): "To crack the RSA cryptosystem, we need the inverse of the QFT." This sets up QPE.
Critical Comparison
| Classical FFT | QFT | |
|---|---|---|
| Input | Explicit sequence of items | Superposition of qubits, whose states represent each item |
| Speedup paradigm | Divide-and-conquer strategy (recursion) | Quantum parallelism (iteration) |
| Time complexity | due to the divide-and-conquer | due to quantum parallelism |
| Space complexity | for all items | |
| Output | Fully readable | Partially readable due to measurement collapse |
| Applications | Standalone data transformer | Subroutine in other quantum algorithms |
- Table 1: Comparison between classical FFT and QFT
❓ Why is QFT "only a subroutine"? Its output is a quantum state. Measuring it collapses it, so you cannot read all Fourier coefficients. It is only useful inside a bigger algorithm (like QPE/Shor) that needs just one peak of the spectrum.
Exercise 6.2: Quantum Fourier Transform
- Show that the cross-correlation operator has time complexity when there are items in the input time series
- Show that the classical Fourier transform has when there are items
- Show that the Fast Fourier Transform algorithm has when there are items
- Show that the quantum Fourier transform algorithm has when there are items
- Discuss how we can encode a time series of items into a mixed state of qubits
- Implement a Python function that converts an input time series of items into a mixed state of qubits. Hint: use
qml.StatePrep(state, wires=...) - Show that the dyadic rational phase gate
- Show that
- Let and be the QFT and InvQFT operators. Show that
3. Quantum Phase Estimation {Exam Q5}
Final Q5 — Shor's Algorithm (QPE part: slides 28–33)
- QPE is the quantum engine inside Shor's algorithm. Expect "why" questions:
- why we need an eigenvector
- what global vs relative phase is
- why the control qubits are in
- why
- why InvQFT
- why
- why QPE is expensive
- See Final - Instructor Hints.
Intuition of Quantum Phase Estimation {Exam Q5}
- If consists of one qubit, we can decompose it into:
- is the relative phase, and is the global phase of
- If a unitary operator has the dominant eigenvector , then
- is the eigenvalue of , which implies that is the global phase of
- Challenge: how can we estimate the phase of any given unitary operator via quantum algorithms?
- Intuition:
- Treat a unitary operator as a rotary movement of the clock, just like the clock's ticking
- This clock rotates with an unknown phase , and we want to approximate it
- Let the clock rotate adequately many times and observe its rotation
- With accumulated uniform rotations, a continuous angular gradient emerges
- Look for the interference pattern and extract the phase from its frequency
📝 Instructor's annotation: arrow onto : "challenge: guess from ".
🎙️ In class (Oct 27-02, 52:23): QPE answers "how could we estimate the rotation period of one quantum program? The gate rotates the input qubit, but you don't know anything inside that gate."
🎙️ In class (Oct 27-02, 54:56): "The relative phase is specific to a particular gate. We can't touch it. But the global phase we can extract automatically. That's the purpose of this algorithm."
🎙️ In class (Nov 3, 17:08–18:23): if is an eigenvector of , then "the output is the quantum state again, the same vector pointing in the same direction, but this time the global phase changes".
❓ Why must be an eigenvector? Only then does act as pure rotation by a fixed angle, with no change of "shape". Repeating times then just multiplies the phase by : . That clean, regular ticking is what the Fourier step can read.
❓ Why is a global phase normally invisible, yet QPE can see it? On its own, has the same probabilities as . But under a controlled-, the phase appears only in the branch of the control. It becomes a relative phase on the control qubit (phase kickback), which interference can then reveal.
Intuition of Quantum Phase Estimation (figure) {Exam Q5}

- Figure 14: four panels
- Treat a unitary operator as one clock's tick with unknown angle
- Rotate the clock with this constant angle
- Keep rotating the clock many times
- Observe the interference pattern and extract its phase
📝 Instructor's annotation: "hint: almost equivalent to extracting a time domain from a frequency domain → InvQFT".
🎙️ In class (Oct 27-02, 56:32–58:48): "Like when you turn on your electric fan, you start to see the blades. The periods you are seeing are the hidden global phase. Rotate the unitary many, many times, then use the inverse QFT to extract the period."
💡 Analogy: Filming a spinning ceiling fan with your phone. At the right shutter speed, the blades look frozen. The shutter speed that freezes them tells you the fan's speed. QPE tries all shutter speeds at once and lets InvQFT tell you which one froze the blades.
Phase Estimation via Uniform Angular Rotations {Exam Q5}

- We imitate angular rotations of with a gate controlled by the -th qubit, called an estimation qubit:
- Since can be treated as an angular rotation of phase :
- We generate adequate angular rotations by a series of exponentials:
- Let be the granularity degree:
📝 Instructor's annotation: drew a circle with a wedge: " rotates by radian". Below: " rotates by radian for times".
🎙️ In class (Oct 27-03, 1:14–4:24): "If this control qubit is , rotate by . If it's , don't rotate. It's a superposition of rotate or not rotate." The next control does , then , , … "How many combinations? . You have tried frequencies."
🎙️ In class (Oct 27-03, 8:13): "This is a constant. With the phase kickback technique, you kick the phase to the other side", from the target register onto the estimation qubits.
❓ Why powers of 2 ()? Any count from to is a binary number . Control qubit switches on or off. So qubits in produce every at once, and the phase lands on the basis state itself.
❓ Why does the phase end up on the control (estimation) register? is an eigenvector, so is times a number. A number can be moved to any factor of a tensor product, so it "kicks back" to the control branch . The target is left unchanged.
💡 Analogy: A row of light switches labelled 1, 2, 4, 8, … turns. Flicking every switch "half-on" (superposition) tries every total number of turns 0… simultaneously.
Decoding the Phase with Inverse Fourier Transform {Exam Q5}
- QFT for the basis state :
- Inverse QFT for the basis state :
- We can decode the phase out of by:
- where the spectrum is
- , i.e. is the leftover after the best -bit approximation
🎙️ In class (Oct 27-03, 6:13): "Once you've got the right frequency, it has the maximum energy. Use the inverse QFT to extract a time domain out of it. Whichever has the highest amplitude is the right frequency, which is the global phase."
❓ Why InvQFT and not QFT? After the rotations, the register holds . That is exactly the QFT output pattern of the basis state . To get back to that basis state, you must undo the QFT, i.e. apply . Mathematically the phases all line up (add constructively) only when . Everywhere else they spin around and cancel.
Probability Distribution for Phase Extraction {Exam Q5}
- Probability for each phase :
- At we extract the phase :
- Summary: we have a unitary operator
- Choose the granularity degree and a random state
- Create a controlled gate : ,
- Accumulate angular rotations:
- Compute the spectrum for each phase:
- Extract the phase , where the optimal
🎙️ In class (Oct 27-03, 11:39–14:10), worked example he drew: granularity gives bars (indices 0–7). The tallest bar is at index 2, so and . "See, it's not that difficult. Choose that bar as and divide by the total number of bars."
❓ Why ? If is not exactly an integer (), the peak leaks into neighbouring bars. Even in the worst case, the best bar still holds at least about 40% of the probability, so a few repetitions find it. If is exactly an integer, .
💡 Analogy: A radio tuner. Every station (index ) gets some static, but the true station's signal adds up "in phase" and comes through loudest.
Implementation of Quantum Phase Estimation Algorithm {Exam Q5}

- The QPE mapping can be simplified as:
- Figure 15: QPE circuit
- estimation wires → H each
- Each estimation wire controls one of , which act on the target register ( qubits)
- Then on the estimation wires → outputs
- Time complexity is , where is the granularity degree
📝 Instructor's annotation: at the first control: "each rotates by radians for times". At : "extract a time domain from a freq. domain".
❓ Why is it ? alone means applying times. Summed over all controls that is applications. More precision (larger ) doubles the cost per extra bit.
❓ Why is unchanged at the output? It is an eigenvector. only multiplies it by a phase, and that phase was kicked back to the estimation register.
Quantum Phase Estimation in PennyLane
- PennyLane:
qml.QuantumPhaseEstimation(opr, target_wires=..., estimation_wires=...)
# opr = unitary operator U
# target_wires = |\psi>
# estimation_wires = phase estimation wires
def qpe(opr, target_wires, estimation_wires):
# Prepare the initial state on the target wires
prep_state(target_wires)
# Prepare the superposition on the estimation wires
for est in estimation_wires:
qml.Hadamard(wires=est)
# Apply angular rotations
qml.ControlledSequence(opr(target_wires), control=estimation_wires)
# Decode the phase by inverse Fourier transform
qml.adjoint(qml.QFT)(wires=estimation_wires)
# Return the probability distribution of phases
return qml.probs(wires=estimation_wires)Practical Strategies for Quantum Phase Estimation
- Challenge: multiplications of are required
| Strategy | Description | Purpose |
|---|---|---|
| Precompute | If is small, we can compute each exponential and include them in the QPE circuit | For small circuits and simulation |
| Transform into | Diagonalize . Then compute . We obtain . | When consists of simple gates |
| Approximate | Break into manageable exponentials with Trotter–Suzuki decomposition (aka trotterization) | For large and composite systems |
- Table 2: Practical solutions to quantum phase estimation
🎙️ In class (Oct 27-03, 21:56–24:47): "QPE poses one technical challenge." If is a long algorithm with for/while loops, then means repeating it 512 times. "It doesn't mean RSA can be cracked so easily. It depends on this . If it's modulo, it's okay."
🎙️ In class (Nov 3, 29:41–32:15): fix = the Hamiltonian (energy form): , so . "Instead of multiplication, you multiply directly into the Hamiltonian." "We can do that by hand as well, which means I'm going to make you do it" (that is Q6, Ch7).
🎙️ In class (Nov 10, 52:53): "That's why QPE is almost practical, because we can approximate to a large power. When QPE becomes practical, you can crack the RSA cryptosystem."
💡 Analogy: Instead of walking to the 512th floor one step at a time, you take the elevator: multiply the "speed" (the Hamiltonian) by 512 once.
Exercise 6.3: Quantum Phase Estimation
- What is the difference between the relative phase and the global phase? Explain briefly.
- Consider the Power Method: , where is a unitary matrix and is large enough. is the dominant eigen-pair of . Explain why applying for adequately many iterations extracts its dominant eigenvector.
- Explain why a quantum operator can be eigen-decomposed to its dominant eigen-pair using QPE.
- Let be the number of estimation qubits. Explain why the operator is rotated for at most iterations.
- Explain how a phase is extracted from multiple rotations using InvQFT.
- Discuss why computing is expensive for some unitary operators .
- Do the numbers of estimation and target qubits need to be equal? Explain your reasons briefly.
- Hint for Q4: .
- Hint for Q7: no. Estimation qubits () set the precision of . Target qubits () must just hold . They are independent (Shor's code uses 8 + 8 only by choice).
4. Shor's Algorithm {Exam Q5}
Final Q5 — Shor's Algorithm (slides 40–41, 44, 47–50, 53–56)
- Mostly "why" questions on the whole pipeline:
- why factorization breaks RSA (slides 48–50)
- why knowing the order gives the factors (slide 47, Fermat–Euler)
- what GCD / coprime / totient mean (slides 40–41, 44)
- how QPE finds (slides 53–54, plus QPE slides 28–33)
- why continued fractions and LCM are needed (slides 55–56)
- the failure cases (odd , )
- The instructor: "What you really have to remember is to guess by quantum algorithms." Key generation details and the proof of correctness are "don't have to focus".
- See Final - Instructor Hints.
Shor in one picture (read this first)
- Goal: factor . Factoring is how you break RSA.
- Guess a number . If , you got lucky and you are done.
- Otherwise, the sequence repeats with some period (the order): . Modulo = rotation, and = how many ticks for one full turn.
- Quantum part: build . Each application is one tick of a clock with ticks per turn, so its phases are . QPE measures one of them as .
- Continued fractions turn into a fraction . Its denominator is (a divisor of) . Take the LCM over a few runs.
- Classical finish: if is even, . So is a factor, unless it is trivial. If it fails, go back to step 2.
Cryptography

- Cryptography: the study and practice of techniques for secure communication in the presence of adversarial behaviours
- The earliest known cryptograph is the Caesar cipher, in which each character is shifted by the position specified in the secret key
- Encryption: HELLO KHOOR
- Decryption: KHOOR HELLO
- Two major types of cryptography:
- Symmetric: encryption and decryption keys are identical, e.g.
- Asymmetric: encryption and decryption keys are different, e.g.
- Modern cryptography is based on the exponential modulo of prime numbers:
- Although we know , it is still computationally expensive to extract
- Figure 16: Caesar cipher with 3 position shifts (A B C D E … V W X Y Z ↔ D E F G H … Y Z A B C)
📝 Instructor's annotation: at the top he drew a wheel cut into slices ≡ a wave with period : "modulo by = rotation with period ".
🎙️ In class (Nov 3, 38:04): "Modulo means rotation… Mark my word: every time you see the modulo, it means rotation, and in every rotation there must be a frequency. That gives you a hint: can we use QPE to extract that number of parts?"
🎙️ In class (Nov 3, 36:39): "Which one is harder to crack, symmetric or asymmetric? They're equally very hard to crack." The Caesar cipher is easy, but that doesn't make all symmetric ciphers easy.
💡 Analogy: A Thai Buddhist-calendar clock: after month 12 you wrap back to month 1. That wrap-around is "mod 12", and its period is 12.
Cryptosystem
- Cryptosystem: a suite of cryptographic algorithms needed to implement a particular security service
- Key generation: the encryption and decryption keys must be generated in pairs and then shared only between the sender and the receiver
- Encryption: an intelligible text is transformed into an unintelligible one using the secret encryption key
- Decryption: an unintelligible text is transformed into an intelligible one using the secret decryption key
- Hashing: data is transformed into a digital signature to evade data tampering, via an irreversible one-to-one function
- Definition: a cryptosystem is a quintuple , where
- is a set of plaintexts, a.k.a. plaintext space
- is a set of ciphertexts, a.k.a. ciphertext space
- is a set of keys, a.k.a. key space
- is a set of encryption functions
- is a set of decryption functions
- For any encryption key , there exists a decryption key such that
🎙️ In class (Nov 3, 40:44): "Every time you see this tuple, don't panic. It just means a cryptosystem consists of five components" (like the finite automaton tuples from TOC).
🎙️ In class (Nov 3, 44:06–45:03): a hash is "like a digital signature for a file". If someone tampers with the file, the signature changes. It is like the last digit of your Thai citizen ID, which is a checksum of the previous 12 digits.
Exercise 6.4: Asymmetric Cryptography
- Modify Caesar's cipher with the exponential modulo of prime numbers:
- is the order of the character (A = 0, B = 1, C = 2, …), is the encryption exponent, and is the modulo
- Let and . Encrypt character by character:
- AND
- HELLO
- MODIFY
- COMPLEX
- Decryption:
- is the encrypted character, is the decryption exponent, and is the modulo
- Let and . Decrypt:
5. [85, 115, 133]
6. [93, 108, 171, 115]
7. [177, 115, 106, 171, 0]
8. [145, 115, 177, 93, 147, 171]
- Note: is exactly the RSA key from slide 50.
Classical Prime Factorization {Exam Q5}
- An integer is a prime number if is divisible by only 1 and
- Prime factorization: find the prime factors of an integer, e.g.
- "": is a prime factor of , e.g.
- Prime factorization takes time, where is the length of the bitstring :
- If , then is a factor.
- Otherwise, pick a random prime , where .
- Compute the greatest common divisor .
- If , then we have found a factor. Carry on with factorizing and recursively.
- Otherwise, go back to step 2.
- Euclid's method for the greatest common divisor of integers :
- Least common multiple of :
📝 Instructor's annotation: "" is labelled "large int " with an arrow ⇓ "prime factors". Beside step 2: "ห.ร.ม. (หารร่วมมาก)" (the Thai name for GCD). Beside LCM: "ค.ร.น. (คูณร่วมน้อย)" (the Thai name for LCM). "greatest common divisor" and "Least common multiple" are highlighted.
🎙️ In class (Nov 3-02, 2:49): "Why ?" If with both factors , then , which is impossible. So the smaller factor is always .
🎙️ In class (Nov 3-02, 4:52–5:53): "It's called guessing. Guess a prime factor. If it's correct, divide." Repeating this loop for huge "makes prime factorization impossible in classical computation. But in quantum computing, no more."
🎙️ In class (Nov 3-02, 11:54): "GCD and LCM are very important in prime factorization. This is how we crack the RSA."
❓ Why is this slow? The number of primes below grows like . That is exponential in the number of bits . A 2048-bit RSA modulus would need about guesses.
Coprimality {Exam Q5}
- Example (Euclid):
- is coprime with if
- Example: 8 and 9 are coprime, because their GCD is 1, even though they are non-prime
- Numbers and are coprime if and only if the numbers and are coprime:
- Bézout's identity: for any coprime there exist integers such that
📝 Instructor's annotation: above the definition: " and don't have GCD other than 1 (จำนวนเฉพาะสัมพัทธ์)" (the Thai term for "relatively prime").
🎙️ In class (Nov 3-02, 13:07–13:48): "Coprime means their GCD is one. They have nothing in common, just like you and your crush." , : no shared prime.
🎙️ In class (Nov 3-02, 15:19): Bézout / extended Euclid: "you don't need to memorize it. I'm showing you the origin of RSA."
❓ Why does Shor need coprime with ? Only then does have an order (), i.e. multiplying by is a reversible "rotation" (a permutation) mod . If , there is no need for quantum at all: the GCD already is a factor.
Extended Euclid's Method
- The GCD of two integers can be written as Bézout's identity , where and
- Example:
- Therefore:
🎙️ In class (Nov 3-02, 43:19): this is where the and in RSA key generation () come from.
Classical Prime Factorization in NumPy
import numpy as np
import numpy.random as rnd
def prepare_primes(n):
flags = np.ones(n, dtype=bool)
flags[0] = flags[1] = False
for i in range(2, n):
if flags[i]:
for j in range(2 * i, n, i):
flags[j] = False
return np.arange(n)[flags]
def factorize(n, primes):
if n == 1: return np.array([n])
potential_factors = primes[primes <= np.sqrt(n)]
for a in potential_factors:
k = np.gcd(n, a)
if k != 1:
return np.hstack([ factorize(k, primes), factorize(n // k, primes) ])
return np.array([n])
primes = prepare_primes(200)
print(factorize(152, primes)) # Expected result: [ 2 2 2 19]prepare_primes= the Sieve of Eratosthenes
Euler's Totient Function {Exam Q5}
- Euler's totient function is the number of integers that are coprime to
- General case: if , where each is a prime factor of , then
- Special case: if is prime, then
- Distributive property: if two integers are coprime, then
- Example: :
- Intuition: gives the order (size) of the multiplicative group of modulo
- The coprimes of 15 are
- We then have
- Some numbers are not in this multiplicative group of modulo 15, such as 3, because can be reduced to , which is in a group of modulo 5
📝 Instructor's annotation: highlighted the definition ("the number of integers that are coprime to ") and, in green, " gives the order (size) of the multiplicative group of modulo ".
🎙️ In class (Nov 3-02, 17:24): "Totient" comes from the Latin totiens ("so many times"), so a totient function counts something. Here it counts coprimes. He walked through 15: 1 ✓, 2 ✓, 3 ✗ (shares 3), 4 ✓, … giving 8.
🎙️ In class (Nov 3-02, 32:01–33:08): for RSA, , so .
🎙️ In class (Oct 27-03, 19:07): "The totient function is the order of modulo. Once you extract the rotation phase, you start to see the factor."
❓ Why does Shor care? is the size of the "clock" of numbers you can multiply mod . Every coprime comes back to 1 after a number of steps that divides (that number is the order ). If you know and , you can solve for . So the totient/order is as secret as the factors themselves.
💡 Analogy: Seats on a Ferris wheel. = the number of seats. Multiplying by = moving the wheel by a fixed jump. The order = how many jumps until your seat returns to the bottom.
Carmichael's Totient Function
- Carmichael's totient function is the smallest positive integer such that, for every integer coprime with ,
- Recursive definition:
- are distinct primes, prime , and is Euler's totient function
- Example: :
🎙️ In class (Nov 3-02, 24:28): "You don't have to remember that. I'm telling you a story behind the RSA." reveals the power that brings any coprime back to 1.
Exercise 6.5: Prime Numbers and Totient Functions
- Compute the GCD and LCM of the following coprime pairs using Euclid's method:
- 4620 and 78
- 53482 and 385
- 148580 and 374
- 3233230 and 4025
- Convert the following coprime pairs into Bézout's identity using the extended Euclid's method:
5. 630 and 66
6. 65065 and 1729
7. 454597 and 2926
8. 8498776 and 7714 - Compute Euler's totient function :
9.
10.
11.
12. - Compute Carmichael's totient function :
13.
14.
15.
16.
Fermat-Euler Theorem {Exam Q5}
- If and are coprime with each other:
- is the order (size) of the multiplicative group of modulo
- Fermat's little theorem: if is a prime, then for any integer (not a multiple of ),
- Consequence: suppose we have large coprimes and . Although is kept secret, we may be able to reveal it, but only if we know and can estimate
- Proof (we know the large coprime ):
- Suppose we can estimate .
- We guess a coprime with , which satisfies the Fermat–Euler theorem:
- If we assume to be even, we can factorize the LHS into
- That means either or shares a factor with . Therefore a prime factor of is either
📝 Instructor's annotation: a red brace with a ★ over "Fermat's little theorem" and "Consequence" (the starred, important part).
🎙️ In class (Nov 3-02, 28:03): "If you can guess that number of the totient function, you can crack right away. That's the key message."
🎙️ In class (Nov 3-02, 28:31–30:25): "Suppose we can estimate it. We call it the order, or the global phase of rotation. Call it . From this theorem, mod is zero. Then factorize it into and , and those are factors of . That's the point."
🎙️ In class (Nov 3-02, 30:37): "For the cyber guys: the order that Pom talks about means the global phase of rotation."
❓ Why must be even? To split as a difference of squares , the exponent must be an integer. If is odd, is not an integer mod , so the trick fails and we must pick a new .
❓ Why does a product give a factor? divides . Unless one bracket is itself a multiple of , must divide one bracket and the other. GCD (cheap, by Euclid) then pulls or out.
⚠️ Failure case: if , then is a multiple of . The GCDs give only the trivial or , so pick another . (This is the ", go back" branch in Shor.)
⚠️ Precise wording: the Shor finds is the order of , the smallest with . It divides (and ). The slides write "". Any multiple of the order also works in .
Asymmetric Cryptography {Exam Q5}

- Asymmetric cryptography: a cryptographic system that uses pairs of related keys
- Generate two large prime numbers .
- Compute .
- Publish as the public key (shared among everyone for encryption), and conceal and as private keys (kept secret for encryption and decryption).
- Encryption and decryption keys depend on the totient
- Attack of asymmetric cryptography: recovering the private keys, or decrypting a message without legitimate access
- Prime numbers make it hard to attack due to mathematical difficulty
- Math difficulty: it is easy to multiply two large prime numbers , but it is intractable to factorize back to and , with time complexity
- Figure 17: "Generate keys" → public key = private key (for encryption) × private key (for decryption). Sender A: Message → Encrypt . Receiver B: Decrypt → Message.
🎙️ In class (Nov 3, 48:10–50:36): "First, select two large primes and . Multiply them: . The encryption key uses and , the decryption key uses and . Both depend on , which we call the totient. Totient means counting."
🎙️ In class (Nov 3, 51:27): "One way to crack it is to find and from . Because is very large, you need to guess."
🎙️ In class (Nov 3-02, 34:30): "If you've got a small , it's really easy to crack. You can do a for loop. You need a large ."
❓ Why is it secure? Multiplying is fast (), but un-multiplying (factoring) has no known fast classical algorithm. That one-way gap is the whole security of RSA. Shor removes the gap.
💡 Analogy: Mixing two paint colours is easy. Un-mixing the result back into the exact original two colours is practically impossible.
Rivest-Shamir-Adleman Cryptosystem (RSA) {Exam Q5}

- RSA is an asymmetric cryptography system widely used in secure data transmission, e.g. Transport Layer Security (TLS)
- Encryption:
- Convert a string into an integer .
- Compute the encrypted message :
- Send to the receiver. (The slide prints "", a typo: the ciphertext is sent.)
- Decryption:
- Receive the encrypted message .
- Compute the decrypted message :
- Convert back to a string .
- Figure 18: "Generate keys" → public key , private key (for encryption), private key (for decryption). Encrypt: . Decrypt: .
🎙️ In class (Oct 27-01, 8:52): "Because of Shor's algorithm, it makes the traditional cyber-security algorithms vulnerable, especially RSA, because it's everywhere in TLS."
🎙️ In class (Nov 3, 15:11): cracking RSA would "make the blockchain unsafe".
❓ Why does decryption work? , so (proof on slide 51).
Key Generation of RSA Cryptosystem {Exam Q5}
- Choose two large primes and , preferably between and . They are kept secret.
- Compute the modulus . Use as part of the public key.
- Compute Carmichael's totient function . Keep secret.
- Choose a coprime with . Use as part of the public key.
- Compute in the equation by solving via the extended Euclid's method. Use as the private key.
- The public key is , while the private key is .
Demonstration
- Choose two primes and .
- Compute the modulus .
- Compute Carmichael's totient .
- Choose , coprime with .
- Solve for :
- (The slide's first line prints "". The correct start is , as in slide 42.)
- Check: ✓
- The public key is , while the private key is .
🎙️ In class (Nov 3-02, 37:27–37:40): "You don't really have to remember that. What you really have to remember is to guess — we can guess by quantum algorithms."
❓ Why does knowing break everything? With the attacker computes , then runs the same extended Euclid to get from the public . So factoring = stealing the private key.
Proof of Correctness
- The starting point is
- Since , is a multiple of . So is divisible by both and :
- Since , we can prove and separately. Both parts are analogous.
- The part:
- Case 1 (): is a multiple of , so is also a multiple of . Thus .
- Case 2 (): . By Fermat's little theorem, .
- The proof of the part is analogous to that of the part.
- Therefore:
🎙️ In class (Nov 3-02, 41:32): "You don't have to focus on that." (But Exercise 6.6 Q4 asks why Fermat's little theorem is crucial: it is exactly step 4, Case 2.)
Exercise 6.6: RSA Cryptosystem
- Suppose we choose two primes and . Generate the public key and the private key .
- Discuss why it is intractable to factorize a large number directly into two multiplicands and , although we know that both are large primes.
- Discuss why the Fermat–Euler theorem makes it easier to factorize a large number that is a product of two large primes.
- Explain why Fermat's little theorem plays a crucial role in the RSA cryptosystem. [Hint: consult its proof of correctness.]
- In practice, text encryption is not done at the character level but at the chunk level. Implement an RSA cryptosystem in NumPy. Encryption and decryption are done in chunks of eight ASCII characters, where each text chunk is encoded by . The system should randomize and , and generate and accordingly.
- Worked hint for Q1: , . Pick (coprime with 176). Solve : (since ). Public , private .
Shor's Algorithm {Exam Q5}

- Shor's algorithm is a classical–quantum hybrid method for factorizing , where and are large prime factors
- Hybrid algorithm: factorize
- If , then is a factor.
- Otherwise, pick a random prime , where .
- Compute the greatest common divisor .
- If , then we have found a factor. Carry on with factorizing and recursively.
- Otherwise, compute the order using quantum phase estimation.
- If is odd, go back to Step 2.
- Otherwise, compute .
- If , go back to Step 2.
- Otherwise, we have found a factor. Carry on with factorizing and recursively.
- Figure 19: flowchart. "Guess factor of " → " divides ?"
- Y → "Factorize and (recursive)"
- N → "Compute order using quantum phase estimation" (with the clock icon) → " is odd?"
- Y → back to Guess
- N → " divides ?"
- N → back to Guess
- Y → "Compute GCD " → "Factorize and (recursive)"
- Time complexity is , where is the length of the bitstring
🎙️ In class (Nov 3-02, 48:09–49:21): "We add just only one additional step to the classical factorization. If you make a wrong guess, you don't really have to fall back to the loop. Convert the modulo function into a quantum operator and rotate it for the right frequency using QPE. That's the frequency of rotation, ."
🎙️ In class (Nov 3-02, 50:56–51:58): "If is odd, go back. It means you cannot solve it. If it's even, compute the GCD of and . If they have nothing in common, the GCD is 1, so it's still a wrong guess: make the next guess. If the GCD is not 1, you found a factor: factorize on one branch and on the other, recursively."
🎙️ In class (Nov 3-02, 52:41; Nov 3-03, 3:53): "This is a guessing game. This is how RSA got cracked. We just speed up the guessing process with QPE. That's it."
🎙️ In class (Nov 3-03, 4:50–5:16): classical factorization is about "big O " in the number itself. Here it is , "where is the number of qubits. That is a different scale."
🎙️ In class (Nov 3-03, 5:28–8:47): "For RSA-256 we need about 1,400 logical qubits. We have about 400 qubits in one system." But "1 logical qubit = about 1,000 physical qubits", so about 1 million physical qubits. "The future is near."
❓ Why each step of Shor (exam-ready)
- Step 2, pick random : we need an "engine" to rotate. Any coprime with gives a periodic sequence . Random choice makes a good (even , no trivial GCD) likely: at least 50% per try.
- Steps 3–4, GCD first: it is cheap (Euclid, ). If already shares a factor with , we are done without any quantum work.
- Step 5, order via QPE: finding classically means computing until 1 appears, which takes up to steps (exponential in ). QPE reads the rotation frequency in polynomial time. This is the only quantum step.
- Step 6, odd → retry: the difference-of-squares split needs an integer .
- Steps 7–8, → retry: the brackets may contain no useful factor. This happens when , where all of hides in one bracket. Then you need a new .
- Step 9, recursion: and may still be composite (e.g. ), so factor them again.
💡 Analogy: A safecracker (classical) tries combinations one by one. Shor's trick: listen to the rhythm of the dial clicks (period ). Once you know the rhythm, simple arithmetic (GCD) tells you the combination. The quantum computer is only the stethoscope.
Worked toy example: factor (not on the slides; for understanding)
- Pick . , so go to the quantum step.
- Powers of 7 mod 15: , , , . So the order is (the sequence 1, 7, 4, 13, 1, 7, … has period 4).
- is even, so :
- ✓
- ✓
- 🎉
- What QPE actually returns (with counting qubits, bars): the phases are , so peaks at .
| measured | fraction | denominator | outcome | |
|---|---|---|---|---|
| 0 | 0 | 1 | no info → run again | |
| 2 | 0.25 | 4 | ✓ | |
| 4 | 0.5 | 2 | only a divisor of () → combine runs | |
| 6 | 0.75 | 4 | ✓ |
- Two runs giving denominators 2 and 4 → . This is why the LCM step exists.
Estimating the Order with Quantum Phase Estimation {Exam Q5}
- Motivation: modulo with order can be seen as a full rotation within steps (the slide writes " steps")
- We can define a unitary operator for modulo as the mapping
- Recall that is the public key and is obtained from guessing
- Precise definition:
- Apply quantum phase estimation to to approximate its phase :
- Since is actually a fraction , where is the optimal phase index, we still have to approximate the order from
- The approximation by a coprime fraction is called the continued fraction method
📝 Instructor's annotation: wrote " :" in front of the mapping.
🎙️ In class (Oct 27-03, 15:42–17:28; Nov 3-02, 53:52): "If you've got the index , the output is modulo . I recompute the index, make it a circle." Example: the modulo-7 operator maps . "When you apply QPE, you start to see the rotation."
🎙️ In class (Nov 3-02, 55:11): "Your phase has the form over 2 to the number of qubits. You approximate it as a fraction where both of them are co-prime."
❓ How the "modular exponentiation" works in practice (what the code does): the gate that is actually run is modular multiplication .
- It is unitary, because is coprime with , so it just permutes .
- Starting from , applying it times gives . That is the slide's .
- The controlled powers are made by multiplying by , computed classically by repeated squaring (, each mod ). In the code:
factor = np.mod(np.power(a, power), n)withpower = 2**k.- So the expensive problem from QPE disappears here: is one multiplication.
❓ Why are the phases ? cycles , a clock with ticks. Its eigenvectors have eigenvalues . So for some .
❓ Why don't we need to know the eigenvector? is an equal mix of all eigenvectors. Starting the target in makes QPE return a random , which is fine, because the denominator is still .
⚠️ Code note: the PennyLane code (slide 60) starts the target in . Since , that state is a fixed point (phase 0), so QPE returns and . The quantum branch then never fires, and 152 is factored by the classical GCD branch. Textbook Shor initialises the target register to .
Continued Fraction Method {Exam Q5}
- A continued fraction is a rational estimate of a real number:
- Continued fraction method:
- Start with index and .
- Let .
- If or hits the limit, then stop.
- Otherwise, compute .
- Increase .
- Go to step 2.
- Example: approximate 1.23456 with a limit of 3:
| 0 | 1.23456 | 1 |
| 1 | 4.26330 | 4 |
| 2 | 3.79793 | 3 |
| 3 | 1.25324 | 1 |
- This gives three convergents:
📝 Instructor's annotation: labelled the three results (numerators , denominators ), ready for the next slide.
🎙️ In class (Nov 3-02, 57:09–59:58): "Floor it, you've got . Take the 0.23456, inverse it, you've got . Floor it, 4. Take the 0.2633, inverse it… Repeat until you're satisfied. The more precision you need, the more tail you add."
🎙️ In class (Nov 3-03, 0:06): "We can guarantee that each pair is co-prime", i.e. every convergent is already in lowest terms.
❓ Why continued fractions? QPE gives a binary fraction (e.g. 0.75 = 6/8). But is generally not a power of 2. Continued fractions find the simplest fraction (smallest denominator) that is very close to . Theory guarantees that if , the true appears among the convergents, and its denominator is the candidate .
💡 Analogy: Recognising as "about 22/7" or "355/113". Continued fractions are the systematic way to find those nice fractions hidden in a long decimal.
Estimating the Order with Continued Fraction Method {Exam Q5}
- Previously we obtained a fraction from quantum phase estimation on :
- Extract convergents of via the continued fraction method:
- We may now treat each as a candidate for the order
- In the original Shor's algorithm, we compute the least common multiple of and use it as the candidate order instead:
- Using the LCM guarantees that we will have a large approximation
- In practice, we can do this automatically by converting into a fraction and then extracting its denominator:
fraction.Fraction(k, 2**N).denominator
🎙️ In class (Nov 3-03, 1:15–2:15): "You don't care about the numerators, you care about the denominators. Compute the LCM of the denominators and you've got , the order, the frequency of rotation. And that is Shor's algorithm."
❓ Why LCM? If the measured shares a factor with (e.g. shows up as ), the denominator is only a divisor of . The LCM of several denominators rebuilds the full (or a multiple of it, which still satisfies ).
⚠️ Failure cases of the quantum part:
- gives no information
- a reduced fraction gives a too-small
- too few counting qubits, or noise, give a wrong convergent
- Always check classically that . If not, rerun QPE.
Shor's Algorithm in PennyLane/1
import pennylane as qml
from pennylane import numpy as np
from pennylane.numpy import random as rnd
from fractions import Fraction
no_targets, no_counts = 8, 8
no_qubits = no_targets + no_counts
wires = range(no_qubits)
counting_wires = range(no_counts)
target_wires = range(no_counts, no_qubits)
dev = qml.device('default.qubit', wires=wires)
def prepare_primes(n):
flags = np.ones(n, dtype=bool)
flags[0] = flags[1] = False
for i in range(2, n):
if flags[i]:
for j in range(2 * i, n, i):
flags[j] = False
return np.arange(n)[flags]
primes = prepare_primes(2 ** no_targets)Shor's Algorithm in PennyLane/2
def factorize_shor(n, primes):
if n == 1:
return np.array([n])
potential_factors = primes[primes <= np.sqrt(n)]
for a in potential_factors:
# Classical factorization
k = np.gcd(n, a)
if k != 1:
return np.hstack([ factorize_shor(k, primes), factorize_shor(n // k, primes) ])
# Quantum speedup
r = find_order(n, a)
if r % 2 == 1: continue
k = np.gcd(n, a ** (r // 2) - 1)
if k != 1:
return np.hstack([ factorize_shor(k, primes), factorize_shor(n // k, primes) ])
return np.array([n])- Note: the code tests , while the slide algorithm tests . Both brackets are valid candidates (slide 47).
Shor's Algorithm in PennyLane/3
def find_order(n, a):
probs = order_finding_circuit(n, a)
idx = int(np.argmax(probs))
frac = Fraction(idx, 2 ** no_counts)
r = frac.denominator
return r
def modulo_matrix(a, power, n):
dims = 2 ** no_targets
mat = np.zeros((dims, dims), dtype=np.complex128)
factor = np.mod(np.power(a, power), n)
for i_input in range(dims):
if i_input < n:
i_output = (factor * i_input) % n
else:
i_output = i_input
mat[i_output, i_input] = 1.0
return mat
def apply_power_modulo(a, power, n, ctrl_wires, tgt_wires):
mat = modulo_matrix(a, power, n)
qml.ctrl(qml.QubitUnitary(mat, wires=tgt_wires), ctrl_wires)modulo_matrixbuilds a permutation matrix: for , and identity for . That is why it is unitary.
Shor's Algorithm in PennyLane/4
@qml.qnode(dev)
def order_finding_circuit(n, a):
init_state = np.zeros(2 ** no_qubits)
init_state[0] = 1.0
qml.StatePrep(init_state, wires=wires)
for i in counting_wires:
qml.Hadamard(wires=i)
for k, ctrl in enumerate(counting_wires):
power = 2 ** k
apply_power_modulo(
a, power, n,
ctrl_wires=[ctrl], tgt_wires=target_wires
)
qml.adjoint(qml.QFT)(wires=counting_wires)
return qml.probs(wires=counting_wires)
print(factorize_shor(152, primes))
# Expected result: [ 2 2 2 19]🎙️ In class (Nov 3-03, 2:27): "This is my own implementation. It's a long code, so we don't really have to focus on that."
- Map to QPE: Hadamards on the counting wires = ;
apply_power_modulo(... 2**k ...)= ;adjoint(QFT)= InvQFT;argmax= ;Fraction(...).denominator= continued fractions.
Exercise 6.7: Shor's Algorithm
- Identify the differences between the classical factorization method and Shor's algorithm.
- Discuss why knowing the order helps speed up classical factorization.
- Explain why the algorithm resorts to classical factorization when is odd. Hint: consult the Fermat–Euler theorem.
- Consider the unitary operator . Explain why applying this operator on is equivalent to rotations.
- Explain why the phase extracted with quantum phase estimation has to be approximated by a fraction , where and are coprime, instead of .
- Answer sketches (these are exactly the "why" questions to expect):
- Q1: classical = blind guessing of until (exponential). Shor = same loop, but on a miss it uses QPE to get the order and builds the factor (polynomial, ).
- Q2: , so one GCD gives a factor directly.
- Q3: odd means is not an integer, so no difference-of-squares split. Choose a new .
- Q4: the controls select every power at once (rotate or not per bit), so all rotation counts happen in superposition.
- Q5: is a power of 2, but is arbitrary. is only a binary approximation of . The continued fraction recovers the exact simple fraction, whose denominator is (coprime ⇒ no hidden common factor).
5. Simon's Algorithm
Simon's Problem
- In cryptography, hashing irreversibly converts an input string into a binary representation
- To avoid collision, hashing is defined as a one-to-one function , where
- A function is NOT one-to-one if and only if for all there is a non-zero solution such that
- In classical computing it is intractable to check this condition on all possible pairs , due to the time complexity
- Quantum solution: test all input strings at the same time and observe the distribution of the outputs
- Figure 20: all inputs 00000000 … 11111111 → cryptographic hash function (lock) → 1-to-1 mapping (balance scale)
🎙️ In class (Nov 3-03, 9:13–12:58): "Shor's algorithm is for cracking RSA. Simon's algorithm is for checking the balance of your hash function." Does the hash cover the whole output space with about the same probability? Classically: a for loop over all inputs. Quantum: all inputs at once. "Same idea as Deutsch, which measures the balance of a function."
Simon's Algorithm
- Daniel R. Simon (1994) proposed an efficient quantum algorithm for checking whether a function is one-to-one
- Force to an extreme, where it generates an output hash code of the same length as the input
- Convert into a quantum operator that maps
- Basic idea: enumerate all possible inputs and solutions of , and measure the distribution of all output hash codes
- First, enumerate all possible inputs :
- Then enumerate all solutions :
📝 Instructor's annotation: labelled as "hash".
🎙️ In class (Nov 3-03, 21:25–21:43): is the binary dot product (bitwise AND, then XOR/parity).
Simon's Algorithm (cont'd)
- By the phase kickback technique:
- The probability of solution is therefore
- Case 1: if is one-to-one, the probability distribution of all solutions is uniform:
- Case 2: if is many-to-one (i.e. non-zero oracle), the probability distribution of all solutions is not uniform
- If is the solution, the range of will be smaller than due to the many-to-one mapping
- We deduce the mapping to their common image by
🎙️ In class (Nov 3-03, 22:25–23:06): "We replace that using the phase kickback. You move everything that is a coefficient from the left-hand side to the right-hand side. It's a constant. Just move it."
🎙️ In class (Nov 3-03, 30:52): the full math proof of the distribution is "beyond our scope, so I'm going to skip this slide".
Implementation of Simon's Algorithm

- Figure 21: input wires → H each → → H each. Output wires → → measure.
🎙️ In class (Nov 3-03, 24:51–25:48): "If you've got a uniform distribution, every possible output has the same probability, so your hash function is good, balanced. If it's imbalanced you have bias, which means a bad hash function." A student added: bias = hash collisions. "The taller the bias, the more collisions."
🎙️ In class (Nov 3-03, 26:21): possible final question: "I have my mysterious hash function and I ran Simon's algorithm. It came up with one of these distributions. Discuss which one is good and which one is bad."
💡 Analogy: Testing whether a lottery machine is fair: pour in every ball at once and see whether every result shows up equally often. Lumps mean some balls collide onto the same number.
Simon's Algorithm in PennyLane
no_qubits = 4
wires = range(2 * no_qubits)
input_wires, output_wires = wires[0 : no_qubits], wires[no_qubits : 2*no_qubits]
dev = qml.device('default.qubit', wires=wires)
def f_mto1(input_wires, output_wires): # Black box function (many to one)
qml.CNOT(wires=[input_wires[3], output_wires[0]]) # Input: |x0, x1, x2, x3>
qml.CNOT(wires=[input_wires[1], output_wires[1]]) # Output: |x3, x1, x0 && x1, x1 && x2>
qml.Toffoli(wires=[input_wires[0], input_wires[1], output_wires[2]])
qml.Toffoli(wires=[input_wires[1], input_wires[2], output_wires[3]])
@qml.qnode(device=dev, shots=1000)
def simon_algo(): # Simon's algorithm
for i in input_wires:
qml.Hadamard(wires=i)
f_mto1(input_wires, output_wires)
for i in input_wires:
qml.Hadamard(wires=i)
return qml.counts(wires=output_wires)
simon_algo()
# Expected result: {'0000': 250, '0100': 62.5, '0101': 62.5, '0110': 62.5, '0111': 62.5,
# '1000': 250, '1100': 62.5, '1101': 62.5, '1110': 62.5, '1111': 62.5}Related
- The hash is built from CNOT and Toffoli (AND) gates. See Lecture 4 - Computation, Measurement, and Dynamic Circuits.
- 🎙️ In class (Nov 3-03, 29:48–30:27): "Please design a quantum algorithm for this logical expression — remember the last midterm question? That will show up again. I spilled the beans." (Said before the official guideline, which lists QML as Q7, so treat it as a possible bonus topic.)
Finding the Solution
- Once we obtain the range of , we discard and due to the lack of information
- Choose the most likely image (i.e. the highest probability) and its linearly independent counterparts
- Solve for the solution from a simple XOR equation system:
- If there is a non-zero solution, we select it as the solution
- Example (from the code above):
- Discard 0000 and 1111 due to no info
- Select 1000, 0111, and 0100
- Solve for :
- This gives , , and , so or
- The non-zero solution is our solution
Exercise 6.8: Simon's Algorithm
- Implement the following hash functions using CNOT, CCX, and other quantum gates in PennyLane. Consult Chapter 4 for the Boolean universality of the Toffoli gate.
- Answer the following questions:
8. Discuss why the hash function of a cryptosystem must be 1-to-1. What issue will we encounter if it is many-to-1?
9. Run Simon's algorithm on the hash functions in Q.1–Q.7 and examine whether they are one-to-one.
10. Find the solutions of the hash functions in Q.1–Q.7 with the XOR equation system.
11. Show that the function is one-to-one if and only if its solution is 0 or 1.
12. Explain why it is intractable to examine all possible input pairs for any function , resulting in time complexity.
🎙️ In class (Nov 3-03, 31:41–32:04): "Look at this question. Each of them is a hash function: design a quantum algorithm for this hash function."
6. Conclusion
Conclusion
- Grover's search algorithm relies on sign-flipping (on the hidden solution) and amplitude amplification
- Quantum Fourier transform (QFT) converts a time series (encoded as a superposition of items) into the frequency domain
- Quantum phase estimation (QPE) extracts the global phase of a unitary operator by rotating it many times and extracting its frequency
- Shor's algorithm speeds up classical prime factorization with QPE on the unitary operator
- Simon's algorithm examines whether a hash function is one-to-one by enumerating all possible inputs, applying them to the function, and measuring the probability distribution of the outputs
🎙️ In class (Nov 3-03, 32:26–33:41): "Shor's algorithm is for guessing a prime factor of a large integer . Once you've got from QPE, compute and try dividing it into . If it works, you found a factor. If not, make another guess. For Simon's, enumerate all inputs, compute the hash, and measure the output distribution. No collision gives uniform, otherwise it is biased."
Target Learning Outcomes
- Grover's Search Algorithm
- Explain the limitation of classical unstructured search () and how Grover's algorithm provides a quadratic speedup ().
- Describe the two core components of the Grover iteration: the oracle function for sign-flipping the solution, and the diffusion operator for amplitude amplification.
- Calculate the optimal number of iterations to avoid overshooting the solution.
- Implement a quantum search routine in PennyLane using
qml.FlipSignandqml.templates.GroverOperator.
- Quantum Fourier Transform (QFT)
- Differentiate between the classical Fast Fourier Transform and the Quantum Fourier Transform in terms of input representation and time complexity.
- Construct the QFT circuit using Fourier blocks composed of Hadamard gates and conditional dyadic rational phase gates.
- Apply the Inverse Quantum Fourier Transform to map frequency-domain vectors back to the time domain.
- Quantum Phase Estimation (QPE)
- Define the concept of a global phase and explain how QPE extracts the phase of a unitary operator given an eigenvector.
- Illustrate the QPE workflow: creating a superposition on estimation qubits, applying controlled-power unitary gates, and decoding via InvQFT.
- Identify practical strategies for large-scale QPE, such as Trotterization or diagonalization of the operator.
- Shor's Algorithm
- Contrast classical prime factorization with the quantum-enhanced speedup.
- Describe the hybrid nature of Shor's algorithm, specifically how it uses QPE to solve the order-finding problem.
- Relate the mathematical foundations of the RSA cryptosystem (Fermat–Euler theorem, Carmichael's function) to the vulnerability addressed by Shor's algorithm.
- Simon's Algorithm
- Formulate Simon's problem as the task of determining whether a hash function is one-to-one or many-to-one.
- Execute the quantum procedure to find the period by measuring output distributions and solving a system of XOR equations.
- Evaluate the security implications of hash collisions in cryptographic systems.