Lecture 6 - Searching and Cryptography

Lecture 6 - Searching and Cryptography

Updated 27 Nov 2026

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 O(n)O(\sqrt n) by sign-flipping and amplitude amplification
  • 2. Quantum Fourier Transform: time series → frequency domain in O((log⁡n)2)O((\log n)^2). 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 rr, 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


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

O(n)where n=size of the search space\boxed{O(n)}\quad\text{where } n = \text{size of the search space}

  • Figure 1: Query → compared against the Keys column → "Match & retrieve" → Values

🎙️ In class (Oct 27, 10:49): O(n)O(n) "sounds okay until you realize you've got billions of documents". Quantum search will not reach O(1)O(1), "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 O(n)O(\sqrt n) 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:

f(x)={1x=xsolution0otherwise\boxed{f(x) = \begin{cases}1 & x = x_{\text{solution}}\\ 0 & \text{otherwise}\end{cases}}

  • Construct the oracle operator by sign-flipping the solution yy:

Uf=∑x≠y∣x⟩⟨x∣⏟non-solutions−∣y⟩⟨y∣⏟solution=∑x≠y(−1)0∣x⟩⟨x∣+(−1)1∣y⟩⟨y∣\mathbf U_f = \underbrace{\sum_{x\neq y}|x\rangle\langle x|}_{\text{non-solutions}} - \underbrace{|y\rangle\langle y|}_{\text{solution}} = \sum_{x\neq y}(-1)^0|x\rangle\langle x| + (-1)^1|y\rangle\langle y|

Uf=∑k=12N(−1)f(BN(k)) ∣BN(k)⟩⟨BN(k)∣Uf∣x⟩=(−1)f(x)∣x⟩\boxed{\mathbf U_f = \sum_{k=1}^{2^N}(-1)^{f(\mathbb B_N(k))}\,|\mathbb B_N(k)\rangle\langle\mathbb B_N(k)|}\qquad \boxed{\mathbf U_f|x\rangle = (-1)^{f(x)}|x\rangle}

📝 Instructor's annotation: wrote "(non-solution: +1)" next to the (−1)0(-1)^0 term and "(solution: −1)" next to the (−1)1(-1)^1 term. Below: Uf: ∣x⟩↦−∣x⟩\mathbf U_f:\ |x\rangle\mapsto-|x\rangle for the solution, and ∣y⟩↦+∣y⟩|y\rangle\mapsto+|y\rangle 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 (∣−a∣2=∣a∣2|-a|^2=|a|^2). 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 y=110y = 110.
    1. Setup: every item has amplitude 1/N1/\sqrt N. The mean vector ss is drawn as a red arrow.
    2. Oracle: the solution is temporarily sign-flipped, so 110110 goes to −1/N-1/\sqrt N
    3. Grover: recompute the mean vector, which shifts from ss to s′s'
    4. 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 ∣x(0)⟩=∣0⟩⊗K|x^{(0)}\rangle = |0\rangle^{\otimes K} and compute the mean vector ∣s(0)⟩=H∣x(0)⟩|s^{(0)}\rangle = \mathbf H|x^{(0)}\rangle
  • Step 2: temporarily sign-flip the solution: ∣q(i)⟩=Uf∣s(i)⟩|q^{(i)}\rangle = \mathbf U_f|s^{(i)}\rangle
  • Step 3: recompute the mean vector: ∣s(i+1)⟩=D H∣q(i)⟩|s^{(i+1)}\rangle = \mathbf D\,\mathbf H|q^{(i)}\rangle
  • Step 4: amplify the probability amplitudes: ∣x(i+1)⟩=H∣s(i+1)⟩|x^{(i+1)}\rangle = \mathbf H|s^{(i+1)}\rangle
  • The diffusion operator D\mathbf D is a Householder reflection through the axis ∣s(i)⟩|s^{(i)}\rangle:

D=2∣0⟩⟨0∣−I\boxed{\mathbf D = 2|0\rangle\langle 0| - \mathbf I}

  • Figure 3: geometric interpretation. The vector y^=∑x≠y∣BN(x)⟩\hat{\mathbf y} = \sum_{x\neq y}|\mathbb B_N(x)\rangle is the sum of non-solutions. The angle always increases by θ\theta.

📝 Instructor's annotation: labelled the axes "solution y\mathbf y" and "y^\hat{\mathbf y}: the sum of non-solutions". Labelled "s(i)s^{(i)}: old mean vector" and "s(i+1)s^{(i+1)}: 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 y^\hat y ("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 θ/2\theta/2 with y^\hat y, so each pull+release turns it by exactly θ\theta towards y\mathbf y.

Optimal Number of Iterations

  • Each iteration recomputes the mean vector ∣s(i+1)⟩|s^{(i+1)}\rangle from ∣s(i)⟩|s^{(i)}\rangle by rotating by a constant angle θ\theta
  • We want to rotate for k∗k^* iterations so that we approximate the solution y\mathbf y, which is perpendicular to the reflection basis y^\hat{\mathbf y}:

k∗θ+θ/2=π/2⇒k∗=⌊π4θ−12⌋k^*\theta + \theta/2 = \pi/2 \quad\Rightarrow\quad k^* = \left\lfloor\frac{\pi}{4\theta} - \frac12\right\rfloor

  • Consider a uniform superposition:

∣s(0)⟩=H(y+y^)=y1n+y^n−1n|s^{(0)}\rangle = \mathbf H(\mathbf y+\hat{\mathbf y}) = \mathbf y\sqrt{\tfrac1n} + \hat{\mathbf y}\sqrt{\tfrac{n-1}{n}}

  • Since ∣s(0)⟩|s^{(0)}\rangle is a unit vector of the form xsin⁡θ+x⊥cos⁡θ\mathbf x\sin\theta + \mathbf x_\perp\cos\theta:

1/n=sin⁡θ≈θfor small θ\sqrt{1/n} = \sin\theta \approx \theta\quad\text{for small }\theta

  • Therefore the optimal number of iterations is

k∗=⌊π4n−12⌋≈⌊π4n⌋n=size of the search space\boxed{k^* = \left\lfloor\frac{\pi}{4}\sqrt n - \frac12\right\rfloor \approx \left\lfloor\frac{\pi}{4}\sqrt n\right\rfloor}\qquad n = \text{size of the search space}

  • Going beyond k∗k^* is called overshooting

📝 Instructor's annotation: drew y\mathbf y vs y^\hat{\mathbf y} with s(k)s^{(k)} rotating towards y\mathbf y by θ\theta: "rotate ss for k∗k^* times". Under the small-angle step: "substitute θ=1/n\theta = \sqrt{1/n} to k∗=⌊π4θ−12⌋k^* = \lfloor \frac{\pi}{4\theta}-\frac12\rfloor".
🎙️ 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 (n−1)/n\sqrt{(n-1)/n} term), until they noticed that nn is millions, so 1/n\sqrt{1/n} is tiny and sin⁡θ≈θ\sin\theta\approx\theta.
🎙️ 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 π/2\pi/2? y⊥y^\mathbf y \perp \hat{\mathbf y}, so the total angle from y^\hat{\mathbf y} to the solution is 90°. Start at θ/2\theta/2, add θ\theta per iteration, and stop when you reach 90°.
❓ Why is it O(n)O(\sqrt n)? k∗≈π4nk^*\approx\frac\pi4\sqrt n iterations, each with one oracle call. Classical search needs O(n)O(n).
💡 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: NN wires start in ∣0⟩|0\rangle, then H on each wire. A dashed box "for i=1i=1 to int(π2N/4\pi\sqrt{2^N}/4)" contains Uf\mathbf U_f → H → D\mathbf D → H. Then measure all NN wires.
  • PennyLane:
    • Steps 1 and 2 are done by qml.FlipSign(statevec, wires=...)
    • Steps 3 and 4 (HDH\mathbf{HDH}) are done by qml.templates.GroverOperator(wires=...)

Grover's Search Algorithm (Actual Implementation)

  • Figure 5: the Grover operator replaces HDH\mathbf{HDH}
    • Initial H on all wires, then Uf\mathbf U_f
    • 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 NN wires

🎙️ In class (Oct 27, 40:36–41:27; 47:12): "This is my D\mathbf D" (TOC joke: "show me your D"). D\mathbf 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 y1,…,ymy_1,\dots,y_m and non-solutions x1,…,xn−mx_1,\dots,x_{n-m}, where n=2Nn=2^N is the size of the search space:

Uf=∑j=1n−m∣xj⟩⟨xj∣⏟non-solutions−∑j=1m∣yj⟩⟨yj∣⏟solutions=∑j=1n−m(−1)0∣xj⟩⟨xj∣+∑j=1m(−1)1∣yj⟩⟨yj∣=∑k=1n(−1)f(BN(k))∣BN(k)⟩⟨BN(k)∣\mathbf U_f = \underbrace{\sum_{j=1}^{n-m}|x_j\rangle\langle x_j|}_{\text{non-solutions}} - \underbrace{\sum_{j=1}^{m}|y_j\rangle\langle y_j|}_{\text{solutions}} = \sum_{j=1}^{n-m}(-1)^0|x_j\rangle\langle x_j| + \sum_{j=1}^{m}(-1)^1|y_j\rangle\langle y_j| = \sum_{k=1}^{n}(-1)^{f(\mathbb B_N(k))}|\mathbb B_N(k)\rangle\langle\mathbb B_N(k)|

  • The optimal number of iterations comes from:

∣s(0)⟩=H(y+y^)=ymn+y^n−mn|s^{(0)}\rangle = \mathbf H(\mathbf y+\hat{\mathbf y}) = \mathbf y\sqrt{\tfrac mn} + \hat{\mathbf y}\sqrt{\tfrac{n-m}{n}}

  • Since ∣s(0)⟩=xsin⁡θ+x⊥cos⁡θ|s^{(0)}\rangle = \mathbf x\sin\theta+\mathbf x_\perp\cos\theta: m/n=sin⁡θ≈θ\sqrt{m/n} = \sin\theta\approx\theta for small θ\theta
  • The optimal number of iterations is

k∗=⌊π4θ−12⌋≈⌊π4nm⌋m=number of solutions\boxed{k^* = \left\lfloor\frac{\pi}{4\theta}-\frac12\right\rfloor \approx \left\lfloor\frac\pi4\sqrt{\frac nm}\right\rfloor}\qquad m = \text{number of solutions}

📝 Instructor's annotation: under ym/n\mathbf y\sqrt{m/n}: "sum of solutions". Under y^(n−m)/n\hat{\mathbf y}\sqrt{(n-m)/n}: "sum of non-solutions".
🎙️ In class (Oct 27, 46:22): with more solutions, fewer iterations are needed. It is still O(n)O(\sqrt n).

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:
    1. 01
    2. 010
    3. 110
    4. 1101
    5. 001 and 100
    6. 1010 and 0101
    7. 010, 011, and 110
    8. all binary representations that consist of one 1 and four 0's
  • Answer the following questions:
    9. Compute the optimal number of iterations k∗k^* for each of the oracle functions in Q.1–Q.8
    10. Compute the rotation angle θ\theta 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: n=24=16n=2^4=16, m=1m=1, so θ≈1/16=0.25\theta\approx\sqrt{1/16}=0.25 and k∗=⌊π/(4⋅0.25)−0.5⌋=⌊2.64⌋=2k^*=\lfloor\pi/(4\cdot0.25)-0.5\rfloor=\lfloor 2.64\rfloor=2.
  • Worked hint for Q.12: past k∗k^* the mean vector rotates past y\mathbf y, so the solution's probability starts to decrease again.

2. Quantum Fourier Transform

Spectral Density

  • A time series f(t)f(t) 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 ω\omega:

Ψ(A,ω,t)=A cis(−ωt+θ)=Ψ0 cis(−ωt)\boxed{\Psi(A,\omega,t) = A\,\text{cis}(-\omega t+\theta) = \Psi_0\,\text{cis}(-\omega t)}

  • Ψ0=A cis(θ)\Psi_0 = A\,\text{cis}(\theta) is its complex amplitude, and θ\theta is its phase
  • We want to transform a time series into spectra (squared amplitudes ∣Ψ0∣2|\Psi_0|^2) 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 A cis θA\,\text{cis}\,\theta". The frequency-axis bars are marked "∣amplitude∣2|\text{amplitude}|^2".
🎙️ 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 x(t)x(t) is a function of ω\omega that reflects how well x(t)x(t) aligns with the unit wave of frequency ω\omega:

F{x}(ω)=x(t)⊙Ψ(1,ω,t)=∫−∞∞x(t)⋅[Ψ(1,ω,t)]∗ dt=∫−∞∞x(t)⋅cis(ωt) dt\boxed{F\{x\}(\omega) = x(t)\odot\Psi(1,\omega,t) = \int_{-\infty}^{\infty}x(t)\cdot[\Psi(1,\omega,t)]^*\,dt = \int_{-\infty}^{\infty}x(t)\cdot\text{cis}(\omega t)\,dt}

  • ⊙\odot is the cross-correlation operator: u⊙v=u⊤v∗\mathbf u\odot\mathbf v = \mathbf u^\top\mathbf v^*
  • The frequency is usually a multiple of 2π2\pi, which is one round of a circle in radians
  • Figure 7: time-domain signal → frequency domain plot of ∣F{x}(ω)∣2|\mathcal F\{x\}(\omega)|^2 at 2π,4π,6π,8π2\pi,4\pi,6\pi,8\pi

❓ 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 2π,4π,6π,8π2\pi,4\pi,6\pi,8\pi take 2, 3, 4, 5 samples. Average the squared amplitudes to get one bar each → spectrum.
  • Time complexity is O(n2)O(n^2) 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 nn bars you take 2+3+…2+3+\dots samples, ∑kk=n(n+1)/2\sum_k k = n(n+1)/2, so O(n2)O(n^2).

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 2K2^K
  • Base case (N=1N=1): F(x[k])=x[k]\mathcal F(x[k]) = x[k]
  • Recursive case (N>1N>1):

p=F[x[k]],q=F ⁣[x ⁣[k+N2]]p = \mathcal F[x[k]],\qquad q = \mathcal F\!\left[x\!\left[k+\tfrac N2\right]\right]

F[x[k]]=p+q×exp⁡ ⁣[−ı^2πkN],F ⁣[x ⁣[k+N2]]=p−q×exp⁡ ⁣[−ı^2πkN]\boxed{\mathcal F[x[k]] = p + q\times\exp\!\left[-\hat\imath\frac{2\pi k}{N}\right],\qquad \mathcal F\!\left[x\!\left[k+\tfrac N2\right]\right] = p - q\times\exp\!\left[-\hat\imath\frac{2\pi k}{N}\right]}

  • Figure 9: split the series into halves, FFT each, pair positions pp and qq that are N/2N/2 apart, and combine. Time complexity O(nlog⁡n)O(n\log n), where nn is the length of x\mathbf x.

📝 Instructor's annotation: braced p,qp, q as "recursive" and the two combine formulas as "combine the recursive results".
🎙️ In class (Oct 27-02, 9:43–10:23): "What is eiθe^{i\theta}? This is your cis, which means you are rotating it. Same amount of phase, one with +, one with −." O(nlog⁡n)O(n\log n) "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 x=[x0,…,xN−1]\mathbf x = [x_0,\dots,x_{N-1}] into a frequency-domain vector y\mathbf y:

yk=1N∑j=0N−1xj rN−jkrN=cis(2π/N)  is the Nth root of unity\boxed{y_k = \frac{1}{\sqrt N}\sum_{j=0}^{N-1}x_j\,r_N^{-jk}}\qquad \boxed{r_N = \text{cis}(2\pi/N)}\ \text{ is the } N^{\text{th}} \text{ root of unity}

  • In quantum computing we treat a time series as a superposition of data points:

[x0,…,x2N−1]  ⇒  1N∑j=02N−1xk ∣BN(j)⟩[x_0,\dots,x_{2^N-1}] \;\Rightarrow\; \frac{1}{\sqrt N}\sum_{j=0}^{2^N-1}x_k\,|\mathbb B_N(j)\rangle

  • Note that 2N2^N data points become NN qubits
  • QFT as a state mapping:

∣BN(k)⟩↦1N∑j=02N−1rNjk ∣BN(j)⟩\boxed{|\mathbb B_N(k)\rangle \mapsto \frac{1}{\sqrt N}\sum_{j=0}^{2^N-1}r_N^{jk}\,|\mathbb B_N(j)\rangle}

  • QFT operator:

F=1N[1111⋯11r1r2r3⋯rN1r2r4r6⋯r2N1r3r6r9⋯r3N⋮⋮⋮⋮⋱⋮1rNr2Nr3N⋯rNN],rN=cis(2π/N)\mathbf F = \frac{1}{\sqrt N}\begin{bmatrix}1&1&1&1&\cdots&1\\1&r^1&r^2&r^3&\cdots&r^N\\1&r^2&r^4&r^6&\cdots&r^{2N}\\1&r^3&r^6&r^9&\cdots&r^{3N}\\\vdots&\vdots&\vdots&\vdots&\ddots&\vdots\\1&r^N&r^{2N}&r^{3N}&\cdots&r^{NN}\end{bmatrix},\qquad r_N=\text{cis}(2\pi/N)

📝 Instructor's annotation: drew a pie/unit circle with one slice of angle 2πN\frac{2\pi}{N} = rNr_N. Highlighted "a superposition of data points".
🎙️ In class (Oct 27-02, 12:22): rNr_N = "the NN-th root of unity, or let's say the NN-th slice of pie". Multiplying by it rotates by one slice.
🎙️ In class (Oct 27-02, 24:09–26:27): e.g. x1∣00⟩+x2∣01⟩+x3∣10⟩+x4∣11⟩x_1|00\rangle + x_2|01\rangle + x_3|10\rangle + x_4|11\rangle. Four elements need two qubits, nn elements need log⁡2n\log_2 n 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 NN ticks. Row kk of the matrix walks around the clock in steps of kk ticks.

Quantum Algorithm for Fourier Transform

  • We imitate the root of unity rNkr_N^k by the dyadic rational phase gate Rk\mathbf R_k:

Rk=[100cis(2π/2k)]Note that R1=H (slide’s claim)\boxed{\mathbf R_k = \begin{bmatrix}1&0\\0&\text{cis}(2\pi/2^k)\end{bmatrix}}\qquad\text{Note that } \mathbf R_1 = \mathbf H \text{ (slide's claim)}

  • Conditional dyadic rational phase gate:

CRk(a∣b)=[100cis(2πb/2k)]⊗I\boxed{\mathbf{CR}_k(a|b) = \begin{bmatrix}1&0\\0&\text{cis}(2\pi b/2^k)\end{bmatrix}\otimes\mathbf I}

  • the first qubit aa is the input/output, and the second qubit bb is the control
  • Self-condition: CRk(x∣x)=Rk(x)\mathbf{CR}_k(x|x) = \mathbf R_k(x)
  • Fourier block: FBN(x1)\mathbf{FB}_N(x_1) maps ∣0⟩|0\rangle to ∣0⟩|0\rangle, and ∣1⟩|1\rangle to cis ⁣(∑k=1N2πxk2k)∣1⟩\text{cis}\!\left(\sum_{k=1}^N\frac{2\pi x_k}{2^k}\right)|1\rangle, upon ∣x1⟩|x_1\rangle:

FBN(x1)=∏k=1NCRk(N)(x1∣xk)\boxed{\mathbf{FB}_N(x_1) = \prod_{k=1}^{N}\mathbf{CR}^{(N)}_k(x_1|x_k)}

  • Figure 10: Fourier block FBN(x1)\mathbf{FB}_N(x_1). Wire ∣x1⟩|x_1\rangle (with a triangle marking the target) passes through R1,R2,R3,…,Rk,…,RN\mathbf R_1,\mathbf R_2,\mathbf R_3,\dots,\mathbf R_k,\dots,\mathbf R_N and outputs ∣y1⟩|y_1\rangle. Each Rk\mathbf R_k (k≥2k\ge2) is controlled by ∣xk⟩|x_k\rangle.

📝 Instructor's annotation: under Rk\mathbf R_k: "rotate ∣1⟩|1\rangle by 2π/2k2\pi/2^k", with a pie slice of angle 2π2k\frac{2\pi}{2^k}. 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 ∣x2…xN⟩|x_2\dots x_N\rangle to a superposition in ∣y1⟩|y_1\rangle".
🎙️ In class (Oct 27-02, 19:34–22:41): "A very scary name, dyadic rational phase gate. I just call it Rk\mathbf R_k: keep ∣0⟩|0\rangle, rotate ∣1⟩|1\rangle by 2π/2k2\pi/2^k." "R1\mathbf R_1 means Hadamard."
⚠️ Note: literally diag(1,cis(π))=diag(1,−1)=Z\text{diag}(1,\text{cis}(\pi)) = \text{diag}(1,-1) = \mathbf Z. In the real circuit the first box on each target wire is a Hadamard (which also uses the −1-1 phase on ∣1⟩|1\rangle). This is why the slide and the PennyLane code put qml.Hadamard there. Exercise 6.2 Q7 asks about this.

Implementation of Quantum Fourier Transform

  • For each qubit yjy_j, map ∣0⟩↦∣0⟩|0\rangle\mapsto|0\rangle and

∣1⟩↦cis ⁣(∑k=1N−j+12πxj+k/2k)∣1⟩|1\rangle\mapsto\text{cis}\!\left(\sum_{k=1}^{N-j+1}2\pi x_{j+k}/2^k\right)|1\rangle

  • Figure 11: QFT = a staircase of Fourier blocks FBN(x1),FBN−1(x2),…,FB2(xN−1),FB1(xN)\mathbf{FB}_N(x_1),\mathbf{FB}_{N-1}(x_2),\dots,\mathbf{FB}_2(x_{N-1}),\mathbf{FB}_1(x_N)
  • Time complexity is O(N2)O(N^2)

📝 Instructor's annotation: under O(N2)O(N^2): "NN = no. qubits → 2N2^N items!"
🎙️ In class (Oct 27-02, 26:33–28:11): block 1 has NN R-gates, block 2 has N−1N-1, and so on, so O(N2)O(N^2) gates. "But NN here is the number of qubits, which accommodates 2N2^N items, so it's O((log⁡n)2)O((\log n)^2). 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 y=[y0,…,yN−1]\mathbf y=[y_0,\dots,y_{N-1}] into a time series x\mathbf x:

xk=1N∑j=0N−1yj rNjk(slide prints 12; the phase of rN is positive)\boxed{x_k = \frac{1}{\sqrt N}\sum_{j=0}^{N-1}y_j\,r_N^{jk}}\qquad\text{(slide prints } \tfrac{1}{\sqrt2}\text{; the phase of } r_N \text{ is positive)}

  • InvQFT as a state mapping:

1N∑j=02N−1rNjk ∣BN(j)⟩↦∣BN(k)⟩\boxed{\frac{1}{\sqrt N}\sum_{j=0}^{2^N-1}r_N^{jk}\,|\mathbb B_N(j)\rangle \mapsto |\mathbb B_N(k)\rangle}

  • InvQFT operator:

F−1=F∗=1N[1111⋯11r−1r−2r−3⋯r−N1r−2r−4r−6⋯r−2N1r−3r−6r−9⋯r−3N⋮⋮⋮⋮⋱⋮1r−Nr−2Nr−3N⋯r−NN]\mathbf F^{-1} = \mathbf F^* = \frac{1}{\sqrt N}\begin{bmatrix}1&1&1&1&\cdots&1\\1&r^{-1}&r^{-2}&r^{-3}&\cdots&r^{-N}\\1&r^{-2}&r^{-4}&r^{-6}&\cdots&r^{-2N}\\1&r^{-3}&r^{-6}&r^{-9}&\cdots&r^{-3N}\\\vdots&\vdots&\vdots&\vdots&\ddots&\vdots\\1&r^{-N}&r^{-2N}&r^{-3N}&\cdots&r^{-NN}\end{bmatrix}

  • Inverse property:

F−1F∣x⟩=FF−1∣x⟩=∣x⟩\boxed{\mathbf F^{-1}\mathbf F|x\rangle = \mathbf F\mathbf F^{-1}|x\rangle = |x\rangle}

🎙️ 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 Rk\mathbf R_k is Rk∗\mathbf R_k^*, "because Rk\mathbf R_k is a Hermitian matrix" (slide wording):

Rk∗=[100cis(−2π/2k)],R1∗=H\mathbf R_k^* = \begin{bmatrix}1&0\\0&\text{cis}(-2\pi/2^k)\end{bmatrix},\qquad \mathbf R_1^* = \mathbf H

  • The inverse of conditional Rk\mathbf R_k:

[CRk(a∣b)]∗=[100cis(−2πb/2k)]⊗I[\mathbf{CR}_k(a|b)]^* = \begin{bmatrix}1&0\\0&\text{cis}(-2\pi b/2^k)\end{bmatrix}\otimes\mathbf I

  • the first qubit aa is the input/output, and the second qubit bb is the control
  • Inverse Fourier block: IFBN(x1)\mathbf{IFB}_N(x_1) maps ∣0⟩|0\rangle to ∣0⟩|0\rangle and ∣1⟩|1\rangle to cis ⁣(−∑k=1N2πxk2k)∣1⟩\text{cis}\!\left(-\sum_{k=1}^N\frac{2\pi x_k}{2^k}\right)|1\rangle, upon ∣x1⟩|x_1\rangle:

IFBN(xj)=∏k=1N[CRk(N)(x1∣xk)]∗\boxed{\mathbf{IFB}_N(x_j) = \prod_{k=1}^N\left[\mathbf{CR}^{(N)}_k(x_1|x_k)\right]^*}

  • Figure 12: inverse Fourier block. Wire ∣y1⟩|y_1\rangle passes through RN∗,…,Rk∗,…,R3∗,R2∗,R1∗\mathbf R_N^*,\dots,\mathbf R_k^*,\dots,\mathbf R_3^*,\mathbf R_2^*,\mathbf R_1^* (mirror order), with the target triangle at the right end → ∣x1⟩|x_1\rangle

📝 Instructor's annotation: "rotate ∣1⟩|1\rangle by (−2π2k)(-\frac{2\pi}{2^k})". The triangle is "target qubit of InvQFT". Text: "extract time domain from ∣y2…yN⟩|y_2\dots y_N\rangle to a superposition in ∣x1⟩|x_1\rangle".
⚠️ Note: the correct reason is that Rk\mathbf R_k is unitary (so its inverse is its conjugate transpose Rk∗\mathbf R_k^*). A diagonal matrix with a complex entry is not Hermitian.

Implementation of Inverse Quantum Fourier Transform

  • For each qubit xjx_j, map ∣0⟩↦∣0⟩|0\rangle\mapsto|0\rangle and

∣1⟩↦cis ⁣(−∑k=1N−j+12πyj+k/2k)∣1⟩|1\rangle\mapsto\text{cis}\!\left(-\sum_{k=1}^{N-j+1}2\pi y_{j+k}/2^k\right)|1\rangle

  • Figure 13: InvQFT (QFT∗\text{QFT}^*) = the QFT staircase mirrored: IFB1(xN)\mathbf{IFB}_1(x_N) first (bottom), up to IFBN(x1)\mathbf{IFB}_N(x_1) last (top). Also O(N2)O(N^2).

🎙️ 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 FFTQFT
InputExplicit sequence of n=2Kn=2^K itemsSuperposition of KK qubits, whose states represent each item
Speedup paradigmDivide-and-conquer strategy (recursion)Quantum parallelism (iteration)
Time complexityO(nlog⁡n)O(n\log n) due to the divide-and-conquerO(K2)=O((log⁡n)2)O(K^2)=O((\log n)^2) due to quantum parallelism
Space complexityO(n)O(n) for all itemsO(K)=O(log⁡n)O(K)=O(\log n)
OutputFully readablePartially readable due to measurement collapse
ApplicationsStandalone data transformerSubroutine 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 nn 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

  1. Show that the cross-correlation operator has O(2K)O(2^K) time complexity when there are 2K2^K items in the input time series
  2. Show that the classical Fourier transform has O(22K)O(2^{2K}) when there are 2K2^K items
  3. Show that the Fast Fourier Transform algorithm has O(K2K)O(K2^K) when there are 2K2^K items
  4. Show that the quantum Fourier transform algorithm has O(K2)O(K^2) when there are 2K2^K items
  5. Discuss how we can encode a time series of 2K2^K items into a mixed state of KK qubits
  6. Implement a Python function that converts an input time series of 2K2^K items into a mixed state of KK qubits. Hint: use qml.StatePrep(state, wires=...)
  7. Show that the dyadic rational phase gate R1=H\mathbf R_1 = \mathbf H
  8. Show that IFBN FBN∣x⟩=∣x⟩\mathbf{IFB}_N\,\mathbf{FB}_N|x\rangle = |x\rangle
  9. Let F\mathbf F and F∗\mathbf F^* be the QFT and InvQFT operators. Show that F∗F=I\mathbf F^*\mathbf F = \mathbf I

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 ∣+⟩|+\rangle
    • why CU2k\mathbf{CU}^{2^k}
    • why InvQFT
    • why θ=k∗/2N\theta = k^*/2^N
    • why QPE is expensive
  • See Final - Instructor Hints.

Intuition of Quantum Phase Estimation {Exam Q5}

  • If ∣ψ⟩|\psi\rangle consists of one qubit, we can decompose it into:

∣ψ⟩=r1 cis θ1∣0⟩+r2 cis θ2∣1⟩=cis θ1(r1∣0⟩+r2 cis(θ2−θ1)∣1⟩)|\psi\rangle = r_1\,\text{cis}\,\theta_1|0\rangle + r_2\,\text{cis}\,\theta_2|1\rangle = \text{cis}\,\theta_1\big(r_1|0\rangle + r_2\,\text{cis}(\theta_2-\theta_1)|1\rangle\big)

  • θ2−θ1\theta_2-\theta_1 is the relative phase, and θ1\theta_1 is the global phase of ∣ψ⟩|\psi\rangle
  • If a unitary operator U\mathbf U has the dominant eigenvector ∣ψ⟩|\psi\rangle, then

U∣ψ⟩=cis(2πθ) ∣ψ⟩\boxed{\mathbf U|\psi\rangle = \text{cis}(2\pi\theta)\,|\psi\rangle}

  • cis(2πθ)\text{cis}(2\pi\theta) is the eigenvalue of ∣ψ⟩|\psi\rangle, which implies that 2πθ2\pi\theta is the global phase of U\mathbf U
  • Challenge: how can we estimate the phase of any given unitary operator via quantum algorithms?
  • Intuition:
    1. Treat a unitary operator U\mathbf U as a rotary movement of the clock, just like the clock's ticking
    2. This clock rotates with an unknown phase 2πθ2\pi\theta, and we want to approximate it
    3. Let the clock rotate adequately many times and observe its rotation
    4. With accumulated uniform rotations, a continuous angular gradient emerges
    5. Look for the interference pattern and extract the phase from its frequency

📝 Instructor's annotation: arrow onto U∣ψ⟩=cis(2πθ)∣ψ⟩\mathbf U|\psi\rangle=\text{cis}(2\pi\theta)|\psi\rangle: "challenge: guess θ\theta from U\mathbf U".
🎙️ 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 ∣ψ⟩|\psi\rangle is an eigenvector of U\mathbf U, 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 ∣ψ⟩|\psi\rangle be an eigenvector? Only then does U\mathbf U act as pure rotation by a fixed angle, with no change of "shape". Repeating U\mathbf U kk times then just multiplies the phase by kk: Uk∣ψ⟩=cis(2πθk)∣ψ⟩\mathbf U^k|\psi\rangle = \text{cis}(2\pi\theta k)|\psi\rangle. 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, cis(2πθ)∣ψ⟩\text{cis}(2\pi\theta)|\psi\rangle has the same probabilities as ∣ψ⟩|\psi\rangle. But under a controlled-U\mathbf U, the phase appears only in the ∣1⟩|1\rangle 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
    1. Treat a unitary operator as one clock's tick with unknown angle 2πθ2\pi\theta
    2. Rotate the clock with this constant angle
    3. Keep rotating the clock many times
    4. Observe the interference pattern and extract its phase θ\theta

📝 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 kk angular rotations of U\mathbf U with a gate CUk\mathbf{CU}^k controlled by the kk-th qubit, called an estimation qubit:

∣0kx⟩↦∣0kx⟩∣1kx⟩↦∣1k⟩⊗(Uk∣x⟩)\boxed{|0_k x\rangle\mapsto|0_k x\rangle\qquad |1_k x\rangle\mapsto|1_k\rangle\otimes\big(\mathbf U^k|x\rangle\big)}

  • Since U\mathbf U can be treated as an angular rotation of phase θ\theta:

Uk∣x⟩=cis(2πθk) ∣x⟩\boxed{\mathbf U^k|x\rangle = \text{cis}(2\pi\theta k)\,|x\rangle}

  • We generate adequate angular rotations by a series of exponentials:

∑k=0N−12k=2N−12−1=2N−1\sum_{k=0}^{N-1}2^k = \frac{2^N-1}{2-1} = 2^N-1

  • Let NN be the granularity degree:

∣y⟩=12N/2∑k=02N−1CUk[∣BN(k)⟩⊗∣ψ⟩]=∏k=0N−1CUk[∣+⟩⊗N⊗∣ψ⟩]=∣+⟩⊗N⊗cis ⁣(∑k=02N−12πθk)∣ψ⟩=cis ⁣(∑k=02N−12πθk)∣+⟩⊗N⊗∣ψ⟩=12N/2(∑k=02N−1cis(2πθk) ∣BN(k)⟩)⊗∣ψ⟩\begin{aligned}|y\rangle &= \frac{1}{2^{N/2}}\sum_{k=0}^{2^N-1}\mathbf{CU}^k\big[|\mathbb B_N(k)\rangle\otimes|\psi\rangle\big] = \prod_{k=0}^{N-1}\mathbf{CU}^k\big[|+\rangle^{\otimes N}\otimes|\psi\rangle\big]\\ &= |+\rangle^{\otimes N}\otimes\text{cis}\!\left(\sum_{k=0}^{2^N-1}2\pi\theta k\right)|\psi\rangle = \text{cis}\!\left(\sum_{k=0}^{2^N-1}2\pi\theta k\right)|+\rangle^{\otimes N}\otimes|\psi\rangle\\ &= \boxed{\frac{1}{2^{N/2}}\left(\sum_{k=0}^{2^N-1}\text{cis}(2\pi\theta k)\,|\mathbb B_N(k)\rangle\right)\otimes|\psi\rangle}\end{aligned}

📝 Instructor's annotation: drew a circle with a wedge: "U\mathbf U rotates ∣x⟩|x\rangle by 2πθ2\pi\theta radian". Below: "Uk\mathbf U^k rotates ∣x⟩|x\rangle by 2πθ2\pi\theta radian for kk times".
🎙️ In class (Oct 27-03, 1:14–4:24): "If this control qubit is ∣1⟩|1\rangle, rotate by U\mathbf U. If it's ∣0⟩|0\rangle, don't rotate. It's a superposition of rotate or not rotate." The next control does U2\mathbf U^2, then U4\mathbf U^4, U8\mathbf U^8, … "How many combinations? 2N2^N. You have tried 2N2^N 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 (U1,U2,U4,…\mathbf U^1,\mathbf U^2,\mathbf U^4,\dots)? Any count kk from 00 to 2N−12^N-1 is a binary number k=∑jbj2jk=\sum_j b_j2^j. Control qubit jj switches U2j\mathbf U^{2^j} on or off. So NN qubits in ∣+⟩|+\rangle produce every kk at once, and the phase cis(2πθk)\text{cis}(2\pi\theta k) lands on the basis state ∣k⟩|k\rangle itself.
❓ Why does the phase end up on the control (estimation) register? ∣ψ⟩|\psi\rangle is an eigenvector, so Uk∣ψ⟩\mathbf U^k|\psi\rangle is ∣ψ⟩|\psi\rangle times a number. A number can be moved to any factor of a tensor product, so it "kicks back" to the control branch ∣k⟩|k\rangle. The target ∣ψ⟩|\psi\rangle 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…2N−12^N-1 simultaneously.

Decoding the Phase with Inverse Fourier Transform {Exam Q5}

  • QFT for the basis state BN(k)\mathbb B_N(k):

QFT∣BN(k)⟩=12N/2∑j=02N−1cis ⁣(2πjk2N)∣BN(j)⟩\boxed{\text{QFT}|\mathbb B_N(k)\rangle = \frac{1}{2^{N/2}}\sum_{j=0}^{2^N-1}\text{cis}\!\left(\frac{2\pi jk}{2^N}\right)|\mathbb B_N(j)\rangle}

  • Inverse QFT QFT∗\text{QFT}^* for the basis state BN(k)\mathbb B_N(k):

QFT∗∣BN(k)⟩=12N/2∑j=02N−1cis ⁣(−2πjk2N)∣BN(j)⟩\boxed{\text{QFT}^*|\mathbb B_N(k)\rangle = \frac{1}{2^{N/2}}\sum_{j=0}^{2^N-1}\text{cis}\!\left(-\frac{2\pi jk}{2^N}\right)|\mathbb B_N(j)\rangle}

  • We can decode the phase out of ∣y1:N⟩|y_{1:N}\rangle by:

∣Ψ⟩=QFT∗∣y1:N⟩=12N/2∑j=02N−1∑k=02N−1cis ⁣(−2πjk2N)×12N/2(cis(2πθk)∣BN(k)⟩)=12N∑j=02N−1[∑k=02N−1cis2πk(2Nθ−j)2N∣BN(k)⟩]=12N∑k=02N−1[∑j=02N−1qj,k]∣BN(k)⟩\begin{aligned}|\Psi\rangle = \text{QFT}^*|y_{1:N}\rangle &= \frac{1}{2^{N/2}}\sum_{j=0}^{2^N-1}\sum_{k=0}^{2^N-1}\text{cis}\!\left(-\frac{2\pi jk}{2^N}\right)\times\frac{1}{2^{N/2}}\big(\text{cis}(2\pi\theta k)|\mathbb B_N(k)\rangle\big)\\ &= \frac{1}{2^N}\sum_{j=0}^{2^N-1}\left[\sum_{k=0}^{2^N-1}\text{cis}\frac{2\pi k(2^N\theta - j)}{2^N}|\mathbb B_N(k)\rangle\right] = \frac{1}{2^N}\sum_{k=0}^{2^N-1}\left[\sum_{j=0}^{2^N-1}q_{j,k}\right]|\mathbb B_N(k)\rangle\end{aligned}

  • where the spectrum is

qj,k=cis2πk(⌊2Nθ⌋+2Nδ−j)2Nq_{j,k} = \text{cis}\frac{2\pi k\big(\lfloor 2^N\theta\rfloor + 2^N\delta - j\big)}{2^N}

  • 2Nθ=⌊2Nθ⌋+2Nδ2^N\theta = \lfloor2^N\theta\rfloor + 2^N\delta, i.e. δ\delta is the leftover after the best NN-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 ∑kcis(2πθk)∣k⟩\sum_k \text{cis}(2\pi\theta k)|k\rangle. That is exactly the QFT output pattern of the basis state ∣2Nθ⟩|2^N\theta\rangle. To get back to that basis state, you must undo the QFT, i.e. apply QFT∗\text{QFT}^*. Mathematically the phases cis(2πk(2Nθ−j)/2N)\text{cis}(2\pi k(2^N\theta-j)/2^N) all line up (add constructively) only when j≈2Nθj\approx2^N\theta. Everywhere else they spin around and cancel.

Probability Distribution for Phase Extraction {Exam Q5}

  • Probability for each phase BN(k)\mathbb B_N(k):

P(k)=12N∣∑j=02N−1qj,k∣2\boxed{P(k) = \frac{1}{2^N}\left|\sum_{j=0}^{2^N-1}q_{j,k}\right|^2}

  • At k=⌊2Nθ⌋k=\lfloor2^N\theta\rfloor we extract the phase θ=k/2N\theta = k/2^N:

P(⌊2Nθ⌋)=12N∣∑j=02N−1cis(2πkδ)∣2=12N∣∑j=02N−1exp⁡(2πikδ)∣2=12N∣1−exp⁡(2N2πikδ)1−exp⁡(2πikδ)∣2  ≥  4π2P(\lfloor2^N\theta\rfloor) = \frac{1}{2^N}\left|\sum_{j=0}^{2^N-1}\text{cis}(2\pi k\delta)\right|^2 = \frac{1}{2^N}\left|\sum_{j=0}^{2^N-1}\exp(2\pi ik\delta)\right|^2 = \frac{1}{2^N}\left|\frac{1-\exp(2^N2\pi ik\delta)}{1-\exp(2\pi ik\delta)}\right|^2 \;\ge\; \boxed{\frac{4}{\pi^2}}

  • Summary: we have a unitary operator U\mathbf U
    1. Choose the granularity degree NN and a random state ∣ψ⟩|\psi\rangle
    2. Create a controlled gate CUk\mathbf{CU}^k: ∣0kx⟩↦∣0kx⟩|0_kx\rangle\mapsto|0_kx\rangle, ∣1kx⟩↦∣1k⟩⊗(Uk∣x⟩)|1_kx\rangle\mapsto|1_k\rangle\otimes(\mathbf U^k|x\rangle)
    3. Accumulate angular rotations: ∣y⟩=∏j=0N−1CUk[(H∣0⟩)⊗N⊗∣ψ⟩]|y\rangle = \prod_{j=0}^{N-1}\mathbf{CU}^k\big[(\mathbf H|0\rangle)^{\otimes N}\otimes|\psi\rangle\big]
    4. Compute the spectrum for each phase: ∣Ψ⟩=QFT∗∣y1:N⟩|\Psi\rangle = \text{QFT}^*|y_{1:N}\rangle
    5. Extract the phase θ=k∗/2N\theta = k^*/2^N, where the optimal k∗=arg⁡max⁡kP(BN(k)∣Ψ)k^* = \arg\max_k P(\mathbb B_N(k)|\Psi)

θ≈k∗2N,k∗=arg⁡max⁡kP(BN(k) ∣ Ψ)\boxed{\theta \approx \frac{k^*}{2^N},\qquad k^* = \arg\max_k P(\mathbb B_N(k)\,|\,\Psi)}

🎙️ In class (Oct 27-03, 11:39–14:10), worked example he drew: granularity N=3N=3 gives 23=82^3=8 bars (indices 0–7). The tallest bar is at index 2, so k∗=2k^*=2 and θ=2/8\theta = 2/8. "See, it's not that difficult. Choose that bar as k∗k^* and divide by the total number of bars."
❓ Why ≥4/π2≈0.405\ge 4/\pi^2\approx0.405? If 2Nθ2^N\theta is not exactly an integer (δ≠0\delta\neq0), 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 2Nθ2^N\theta is exactly an integer, P=1P=1.
💡 Analogy: A radio tuner. Every station (index kk) 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:

QPE(∣0⟩⊗N⊗∣ψ⟩)=∣BN(k∗)⟩⊗∣ψ⟩\boxed{\text{QPE}\big(|0\rangle^{\otimes N}\otimes|\psi\rangle\big) = |\mathbb B_N(k^*)\rangle\otimes|\psi\rangle}

  • Figure 15: QPE circuit
    • NN estimation wires ∣0⟩|0\rangle → H each
    • Each estimation wire controls one of U1,U2,U4,U8,…,U2N−1\mathbf U^1,\mathbf U^2,\mathbf U^4,\mathbf U^8,\dots,\mathbf U^{2^{N-1}}, which act on the target register ∣ψ⟩|\psi\rangle (MM qubits)
    • Then QFT∗\text{QFT}^* on the estimation wires → outputs ∣k1⟩,…,∣kN⟩|k_1\rangle,\dots,|k_N\rangle
  • Time complexity is O(2N)O(2^N), where NN is the granularity degree

📝 Instructor's annotation: at the first control: "each Uk\mathbf U^k rotates ∣ψ⟩|\psi\rangle by 2πθ2\pi\theta radians for kk times". At QFT∗\text{QFT}^*: "extract a time domain from a freq. domain".
❓ Why is it O(2N)O(2^N)? U2N−1\mathbf U^{2^{N-1}} alone means applying U\mathbf U 2N−12^{N-1} times. Summed over all controls that is 2N−12^N-1 applications. More precision (larger NN) doubles the cost per extra bit.
❓ Why is ∣ψ⟩|\psi\rangle unchanged at the output? It is an eigenvector. U\mathbf U 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: O(2N)O(2^N) multiplications of U\mathbf U are required
StrategyDescriptionPurpose
Precompute U2k\mathbf U^{2^k}If U\mathbf U is small, we can compute each exponential U2k\mathbf U^{2^k} and include them in the QPE circuitFor small circuits and simulation
Transform U\mathbf U into exp⁡(−iH^)\exp(-i\hat{\mathbf H})Diagonalize U=VDV∗\mathbf U=\mathbf{VDV}^*. Then compute H^=V(log⁡D)V∗\hat{\mathbf H}=\mathbf V(\log\mathbf D)\mathbf V^*. We obtain U2k=exp⁡(−i2kH^)\mathbf U^{2^k}=\exp(-i2^k\hat{\mathbf H}).When U\mathbf U consists of simple gates
Approximate U2k\mathbf U^{2^k}Break U\mathbf U 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 U\mathbf U is a long algorithm with for/while loops, then U29=U512\mathbf U^{2^9}=\mathbf U^{512} means repeating it 512 times. "It doesn't mean RSA can be cracked so easily. It depends on this U\mathbf U. If it's modulo, it's okay."
🎙️ In class (Nov 3, 29:41–32:15): fix = the Hamiltonian (energy form): U=exp⁡(−iH)\mathbf U=\exp(-i\mathbf H), so Un=exp⁡(−inH)\mathbf U^n = \exp(-in\mathbf H). "Instead of multiplication, you multiply nn 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 U\mathbf U 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

  1. What is the difference between the relative phase and the global phase? Explain briefly.
  2. Consider the Power Method: U(UN∣x⟩)≈λ(UN∣x⟩)\mathbf U(\mathbf U^N|x\rangle)\approx\lambda(\mathbf U^N|x\rangle), where U\mathbf U is a unitary matrix and NN is large enough. (UN∣x⟩,λ)(\mathbf U^N|x\rangle,\lambda) is the dominant eigen-pair of U\mathbf U. Explain why applying U\mathbf U for adequately many iterations extracts its dominant eigenvector.
  3. Explain why a quantum operator can be eigen-decomposed to its dominant eigen-pair using QPE.
  4. Let NN be the number of estimation qubits. Explain why the operator U\mathbf U is rotated for at most 2N2^N iterations.
  5. Explain how a phase θ\theta is extracted from multiple rotations using InvQFT.
  6. Discuss why computing CU2k\mathbf{CU}^{2^k} is expensive for some unitary operators U\mathbf U.
  7. Do the numbers of estimation and target qubits need to be equal? Explain your reasons briefly.
  • Hint for Q4: ∑k=0N−12k=2N−1\sum_{k=0}^{N-1}2^k = 2^N-1.
  • Hint for Q7: no. Estimation qubits (NN) set the precision of θ\theta. Target qubits (MM) must just hold ∣ψ⟩|\psi\rangle. 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 rr gives the factors (slide 47, Fermat–Euler)
    • what GCD / coprime / totient mean (slides 40–41, 44)
    • how QPE finds rr (slides 53–54, plus QPE slides 28–33)
    • why continued fractions and LCM are needed (slides 55–56)
    • the failure cases (odd rr, g=1g=1)
  • The instructor: "What you really have to remember is to guess rr 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)

  1. Goal: factor n=pqn=pq. Factoring nn is how you break RSA.
  2. Guess a number aa. If gcd⁡(a,n)≠1\gcd(a,n)\neq1, you got lucky and you are done.
  3. Otherwise, the sequence a0,a1,a2,… mod na^0, a^1, a^2,\dots \bmod n repeats with some period rr (the order): ar≡1(modn)a^r\equiv1\pmod n. Modulo = rotation, and rr = how many ticks for one full turn.
  4. Quantum part: build Ua∣x⟩=∣a x mod n⟩\mathbf U_a|x\rangle=|a\,x\bmod n\rangle. Each application is one tick of a clock with rr ticks per turn, so its phases are m/rm/r. QPE measures one of them as k∗/2L≈m/rk^*/2^L\approx m/r.
  5. Continued fractions turn k∗/2Lk^*/2^L into a fraction m/rm/r. Its denominator is (a divisor of) rr. Take the LCM over a few runs.
  6. Classical finish: if rr is even, ar−1=(ar/2−1)(ar/2+1)≡0(modn)a^r-1=(a^{r/2}-1)(a^{r/2}+1)\equiv0\pmod n. So gcd⁡(ar/2±1, n)\gcd(a^{r/2}\pm1,\,n) 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 ⇒e=+3\Rightarrow_{e=+3} KHOOR
    • Decryption: KHOOR ⇒d=−3\Rightarrow_{d=-3} HELLO
  • Two major types of cryptography:
    • Symmetric: encryption and decryption keys are identical, e.g. (a⊕e)⊕e=a(a\oplus e)\oplus e = a
    • Asymmetric: encryption and decryption keys are different, e.g. (a+e)+d=a(a+e)+d = a
  • Modern cryptography is based on the exponential modulo of prime numbers:

encrypt(a∣b,p)=(ab) % pb is a prime number\boxed{\text{encrypt}(a|b,p) = (a^b)\,\%\,p}\qquad b \text{ is a prime number}

  • Although we know pp, it is still computationally expensive to extract bb
  • 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 pp slices ≡ a wave with period pp: "modulo by pp = rotation with period pp".
🎙️ 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 (P,C,K,E,D)(P,C,K,E,D), where
    • PP is a set of plaintexts, a.k.a. plaintext space
    • CC is a set of ciphertexts, a.k.a. ciphertext space
    • KK is a set of keys, a.k.a. key space
    • E={Ek∣k∈K}E=\{E_k|k\in K\} is a set of encryption functions P↦CP\mapsto C
    • D={Dk∣k∈K}D=\{D_k|k\in K\} is a set of decryption functions C↦PC\mapsto P
  • For any encryption key e∈Ke\in K, there exists a decryption key d∈Kd\in K such that

Dd(Ee(w))=wfor all plaintexts w∈P\boxed{D_d(E_e(w)) = w\quad\text{for all plaintexts } w\in P}

🎙️ 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: encrypt(a∣b,p)=(ab)%p\text{encrypt}(a|b,p) = (a^b)\%p
    • aa is the order of the character (A = 0, B = 1, C = 2, …), bb is the encryption exponent, and pp is the modulo
    • Let b=7b=7 and p=187p=187. Encrypt character by character:
      1. AND
      2. HELLO
      3. MODIFY
      4. COMPLEX
  • Decryption: decrypt(c∣d,p)=(cd)%p\text{decrypt}(c|d,p) = (c^d)\%p
    • cc is the encrypted character, dd is the decryption exponent, and pp is the modulo
    • Let d=23d=23 and p=187p=187. Decrypt:
      5. [85, 115, 133]
      6. [93, 108, 171, 115]
      7. [177, 115, 106, 171, 0]
      8. [145, 115, 177, 93, 147, 171]
  • Note: (n=187,e=7,d=23)(n=187,e=7,d=23) is exactly the RSA key from slide 50.

Classical Prime Factorization {Exam Q5}

  • An integer NN is a prime number if NN is divisible by only 1 and NN
  • Prime factorization: find the prime factors of an integer, e.g. 150=5×5×3×2150 = 5\times5\times3\times2
  • "p∣np|n": pp is a prime factor of nn, e.g. 5∣1505|150
  • Prime factorization takes O(2LL2)O(2^LL^2) time, where LL is the length of the bitstring nn:
    1. If N=1N=1, then NN is a factor.
    2. Otherwise, pick a random prime aa, where 1<a<N1<a<\sqrt N.
    3. Compute the greatest common divisor k=gcd⁡(N,a)k=\gcd(N,a).
    4. If k≠1k\neq1, then we have found a factor. Carry on with factorizing kk and N/kN/k recursively.
    5. Otherwise, go back to step 2.
  • Euclid's method for the greatest common divisor of integers a,b≥0a,b\ge0:

gcd⁡(a,b)={gcd⁡(b,a)a<bgcd⁡(b, a%b)b>0aotherwisea%b=a−b⌊ab⌋\boxed{\gcd(a,b) = \begin{cases}\gcd(b,a) & a<b\\ \gcd(b,\,a\%b) & b>0\\ a & \text{otherwise}\end{cases}}\qquad a\%b = a - b\left\lfloor\frac ab\right\rfloor

  • Least common multiple of a,b≥0a,b\ge0:

lcm(a,b)=∣ab∣gcd⁡(a,b)\boxed{\text{lcm}(a,b) = \frac{|ab|}{\gcd(a,b)}}

📝 Instructor's annotation: "NN" is labelled "large int NN" 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 n\sqrt n?" If n=xyn = xy with both factors >n>\sqrt n, then xy>nxy>n, which is impossible. So the smaller factor is always ≤n\le\sqrt n.
🎙️ 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 nn "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 n\sqrt n grows like n=2L/2\sqrt n = 2^{L/2}. That is exponential in the number of bits LL. A 2048-bit RSA modulus would need about 210242^{1024} guesses.

Coprimality {Exam Q5}

  • Example (Euclid):

gcd⁡(525,252)=gcd⁡(252,525%252)=gcd⁡(252,21)=gcd⁡(21,252%21)=gcd⁡(21,0)=21\gcd(525,252) = \gcd(252,525\%252) = \gcd(252,21) = \gcd(21,252\%21) = \gcd(21,0) = 21

lcm(525,252)=525×252gcd⁡(525,252)=525×25221=6300\text{lcm}(525,252) = \frac{525\times252}{\gcd(525,252)} = \frac{525\times252}{21} = 6300

  • aa is coprime with bb if

gcd⁡(a,b)=1\boxed{\gcd(a,b)=1}

  • Example: 8 and 9 are coprime, because their GCD is 1, even though they are non-prime
  • Numbers aa and bb are coprime if and only if the numbers 2a−12^a-1 and 2b−12^b-1 are coprime:

gcd⁡(na−1, nb−1)=ngcd⁡(a,b)−1\gcd(n^a-1,\,n^b-1) = n^{\gcd(a,b)}-1

  • Bézout's identity: for any coprime a,ba,b there exist integers x,yx,y such that

ax+by=gcd⁡(a,b)\boxed{ax+by=\gcd(a,b)}

📝 Instructor's annotation: above the definition: "aa and bb 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." 8=2⋅2⋅28=2\cdot2\cdot2, 9=3⋅39=3\cdot3: 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 aa coprime with nn? Only then does aa have an order (ar≡1a^r\equiv1), i.e. multiplying by aa is a reversible "rotation" (a permutation) mod nn. If gcd⁡(a,n)≠1\gcd(a,n)\neq1, there is no need for quantum at all: the GCD already is a factor.

Extended Euclid's Method

  • The GCD gg of two integers a,b>0a,b>0 can be written as Bézout's identity ax+by=gax+by=g, where (g,x,y)=egcd(a,1,0 ∣ b,0,1)(g,x,y)=\text{egcd}(a,1,0\,|\,b,0,1) and

egcd(a,xa,ya ∣ b,xb,yb)={egcd(b,xb,yb ∣ a%b,  xa−qxb,  ya−qyb)b≠0 and q=⌊a/b⌋(a,xa,ya)otherwise\text{egcd}(a,x_a,y_a\,|\,b,x_b,y_b) = \begin{cases}\text{egcd}(b,x_b,y_b\,|\,a\%b,\;x_a-qx_b,\;y_a-qy_b) & b\neq0 \text{ and } q=\lfloor a/b\rfloor\\ (a,x_a,y_a) & \text{otherwise}\end{cases}

  • Example:

egcd(525,1,0 ∣ 252,0,1)=  egcd(252,0,1 ∣ 21,  1−2×0,  0−2×1)=egcd(252,0,1 ∣ 21,1,−2)=  egcd(21,1,−2 ∣ 0,  0−12×1,  1−12×(−2))=egcd(21,1,−2 ∣ 0,−12,25)=  (21,1,−2)⇒(g,x,y)\begin{aligned}&\text{egcd}(525,1,0\,|\,252,0,1)\\ =\;&\text{egcd}(252,0,1\,|\,21,\;1-2\times0,\;0-2\times1) = \text{egcd}(252,0,1\,|\,21,1,-2)\\ =\;&\text{egcd}(21,1,-2\,|\,0,\;0-12\times1,\;1-12\times(-2)) = \text{egcd}(21,1,-2\,|\,0,-12,25)\\ =\;&(21,1,-2)\Rightarrow(g,x,y)\end{aligned}

  • Therefore: 525×1+252×(−2)=21525\times1 + 252\times(-2) = 21

🎙️ In class (Nov 3-02, 43:19): this is where the kk and dd in RSA key generation (λ(n)k+ed=1\lambda(n)k+ed=1) 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 ϕ(n)\phi(n) is the number of integers 1≤k≤n1\le k\le n that are coprime to nn
  • General case: if n=p1k1p2k2p3k3⋯prkrn=p_1^{k_1}p_2^{k_2}p_3^{k_3}\cdots p_r^{k_r}, where each p1,…,prp_1,\dots,p_r is a prime factor of nn, then

ϕ(n)=∏j=1rpjkj−1(pj−1)\boxed{\phi(n) = \prod_{j=1}^{r}p_j^{k_j-1}(p_j-1)}

  • Special case: if nn is prime, then

ϕ(nk)=nk−1(n−1)\boxed{\phi(n^k) = n^{k-1}(n-1)}

  • Distributive property: if two integers p,qp,q are coprime, then

ϕ(pq)=ϕ(p)×ϕ(q)\boxed{\phi(pq)=\phi(p)\times\phi(q)}

  • Example: 200=23×52200 = 2^3\times5^2:

ϕ(200)=ϕ(23×52)=ϕ(23)×ϕ(52)=[22×(2−1)]×[51×(5−1)]=80\phi(200)=\phi(2^3\times5^2)=\phi(2^3)\times\phi(5^2) = [2^2\times(2-1)]\times[5^1\times(5-1)] = 80

  • Intuition: ϕ(n)\phi(n) gives the order (size) of the multiplicative group of modulo nn
    • The coprimes of 15 are {1,2,4,7,8,11,13,14}\{1,2,4,7,8,11,13,14\}
    • We then have ϕ(15)=8\phi(15)=8
    • Some numbers are not in this multiplicative group of modulo 15, such as 3, because x%15=3x\%15=3 can be reduced to x%5=1x\%5=1, which is in a group of modulo 5

📝 Instructor's annotation: highlighted the definition ("the number of integers 1≤k≤n1\le k\le n that are coprime to nn") and, in green, "ϕ(n)\phi(n) gives the order (size) of the multiplicative group of modulo nn".
🎙️ 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, n=pq=p1q1n=pq=p^1q^1, so ϕ(n)=p0(p−1) q0(q−1)=(p−1)(q−1)\phi(n)=p^0(p-1)\,q^0(q-1) = \boxed{(p-1)(q-1)}.
🎙️ 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? ϕ(n)\phi(n) is the size of the "clock" of numbers you can multiply mod nn. Every coprime aa comes back to 1 after a number of steps that divides ϕ(n)\phi(n) (that number is the order rr). If you know ϕ(n)=(p−1)(q−1)\phi(n)=(p-1)(q-1) and n=pqn=pq, you can solve for p,qp,q. So the totient/order is as secret as the factors themselves.
💡 Analogy: Seats on a Ferris wheel. ϕ(n)\phi(n) = the number of seats. Multiplying by aa = moving the wheel by a fixed jump. The order rr = how many jumps until your seat returns to the bottom.

Carmichael's Totient Function

  • Carmichael's totient function λ(n)\lambda(n) is the smallest positive integer mm such that, for every integer aa coprime with nn,

(am)%n=1always holds\boxed{(a^m)\%n = 1}\quad\text{always holds}

  • Recursive definition:

λ(n)={ϕ(n)n∈{1,2,4} or n=poddk12ϕ(n)n=2r and r≥3lcm(λ(p1k1),…,λ(prkr))n=p1k1⋯prkr\lambda(n) = \begin{cases}\phi(n) & n\in\{1,2,4\}\text{ or } n=p_{\text{odd}}^k\\ \tfrac12\phi(n) & n=2^r \text{ and } r\ge3\\ \text{lcm}(\lambda(p_1^{k_1}),\dots,\lambda(p_r^{k_r})) & n=p_1^{k_1}\cdots p_r^{k_r}\end{cases}

  • p1,…,prp_1,\dots,p_r are distinct primes, prime podd≥3p_{\text{odd}}\ge3, and ϕ(n)\phi(n) is Euler's totient function
  • Example: 200=23×52200=2^3\times5^2:

λ(200)=lcm(λ(23),λ(52))=lcm(12ϕ(23),λ(52))=lcm(12×4,λ(52))=lcm(2,ϕ(52))=lcm(2,20)=2×20gcd⁡(2,20)=20\lambda(200) = \text{lcm}(\lambda(2^3),\lambda(5^2)) = \text{lcm}(\tfrac12\phi(2^3),\lambda(5^2)) = \text{lcm}(\tfrac12\times4,\lambda(5^2)) = \text{lcm}(2,\phi(5^2)) = \text{lcm}(2,20) = \frac{2\times20}{\gcd(2,20)} = 20

🎙️ In class (Nov 3-02, 24:28): "You don't have to remember that. I'm telling you a story behind the RSA." λ(n)\lambda(n) reveals the power mm 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:
    1. 4620 and 78
    2. 53482 and 385
    3. 148580 and 374
    4. 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 ϕ\phi:
    9. ϕ(33×53×74)\phi(3^3\times5^3\times7^4)
    10. ϕ(54×63×112)\phi(5^4\times6^3\times11^2)
    11. ϕ(63×103×21)\phi(6^3\times10^3\times21)
    12. ϕ(27×11×17)\phi(2^7\times11\times17)
  • Compute Carmichael's totient function λ\lambda:
    13. λ(26)\lambda(2^6)
    14. λ(54)\lambda(5^4)
    15. λ(83×72)\lambda(8^3\times7^2)
    16. λ(63×212)\lambda(6^3\times21^2)

Fermat-Euler Theorem {Exam Q5}

  • If nn and aa are coprime with each other:

(aϕ(n))%n=1\boxed{\big(a^{\phi(n)}\big)\%n = 1}

  • ϕ(n)\phi(n) is the order (size) of the multiplicative group of modulo nn
  • Fermat's little theorem: if pp is a prime, then for any integer aa (not a multiple of pp),

(ap−1)%p=1\boxed{\big(a^{p-1}\big)\%p = 1}

  • Consequence: suppose we have large coprimes nn and aa. Although aa is kept secret, we may be able to reveal it, but only if we know nn and can estimate ϕ(n)\phi(n)
  • Proof (we know the large coprime nn):
    1. Suppose we can estimate r≈ϕ(n)r\approx\phi(n).
    2. We guess a coprime aa with nn, which satisfies the Fermat–Euler theorem: (ar−1)%n=0(a^r-1)\%n = 0
    3. If we assume rr to be even, we can factorize the LHS into

[(ar/2+1)(ar/2−1)]%n=0\big[(a^{r/2}+1)(a^{r/2}-1)\big]\%n = 0

  1. That means either ar/2+1a^{r/2}+1 or ar/2−1a^{r/2}-1 shares a factor with nn. Therefore a prime factor of nn is either

gcd⁡(ar/2+1, n)orgcd⁡(ar/2−1, n)\boxed{\gcd(a^{r/2}+1,\,n)\quad\text{or}\quad\gcd(a^{r/2}-1,\,n)}

📝 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 nn 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 rr. From this theorem, ar−1a^r-1 mod nn is zero. Then factorize it into ar/2+1a^{r/2}+1 and ar/2−1a^{r/2}-1, and those are factors of nn. 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 rr be even? To split ar−1a^r-1 as a difference of squares (ar/2)2−12(a^{r/2})^2-1^2, the exponent r/2r/2 must be an integer. If rr is odd, ar/2a^{r/2} is not an integer mod nn, so the trick fails and we must pick a new aa.
❓ Why does a product ≡0\equiv0 give a factor? n=pqn=pq divides (ar/2+1)(ar/2−1)(a^{r/2}+1)(a^{r/2}-1). Unless one bracket is itself a multiple of nn, pp must divide one bracket and qq the other. GCD (cheap, by Euclid) then pulls pp or qq out.
⚠️ Failure case: if ar/2≡−1(modn)a^{r/2}\equiv-1\pmod n, then ar/2+1a^{r/2}+1 is a multiple of nn. The GCDs give only the trivial nn or 11, so pick another aa. (This is the "g=1g=1, go back" branch in Shor.)
⚠️ Precise wording: the rr Shor finds is the order of aa, the smallest rr with ar≡1a^r\equiv1. It divides ϕ(n)\phi(n) (and λ(n)\lambda(n)). The slides write "r≈ϕ(n)r\approx\phi(n)". Any multiple of the order also works in ar≡1a^r\equiv1.

Asymmetric Cryptography {Exam Q5}

  • Asymmetric cryptography: a cryptographic system that uses pairs of related keys
    1. Generate two large prime numbers p,qp,q.
    2. Compute n=pqn=pq.
    3. Publish nn as the public key (shared among everyone for encryption), and conceal pp and qq as private keys (kept secret for encryption and decryption).
    4. Encryption and decryption keys depend on the totient

ϕ(n)=(p−1)(q−1)\boxed{\phi(n) = (p-1)(q-1)}

  • 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 p×q=np\times q = n, but it is intractable to factorize nn back to pp and qq, with time complexity O(n(log⁡n)2)O(n(\log n)^2)
  • Figure 17: "Generate keys" → public key nn = private key pp (for encryption) × private key qq (for decryption). Sender A: Message → Encrypt (n,p)(n,p). Receiver B: Decrypt (n,q)(n,q) → Message.

🎙️ In class (Nov 3, 48:10–50:36): "First, select two large primes pp and qq. Multiply them: nn. The encryption key uses nn and pp, the decryption key uses nn and qq. Both depend on (p−1)(q−1)(p-1)(q-1), which we call the totient. Totient means counting."
🎙️ In class (Nov 3, 51:27): "One way to crack it is to find pp and qq from nn. Because nn is very large, you need to guess."
🎙️ In class (Nov 3-02, 34:30): "If you've got a small nn, it's really easy to crack. You can do a for loop. You need a large nn."
❓ Why is it secure? Multiplying is fast (O(L2)O(L^2)), 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:
    1. Convert a string MM into an integer mm.
    2. Compute the encrypted message cc:

c=(me) % n\boxed{c = (m^e)\,\%\,n}

  1. Send cc to the receiver. (The slide prints "mm", a typo: the ciphertext cc is sent.)
  • Decryption:
    1. Receive the encrypted message cc.
    2. Compute the decrypted message mm:

m=(cd) % n=(med) % n\boxed{m = (c^d)\,\%\,n = (m^{ed})\,\%\,n}

  1. Convert mm back to a string MM.
  • Figure 18: "Generate keys" → public key nn, private key ee (for encryption), private key dd (for decryption). Encrypt: c=(me)%nc=(m^e)\%n. Decrypt: m=(cd)%nm=(c^d)\%n.

🎙️ 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? ed≡1(modλ(n))ed\equiv1\pmod{\lambda(n)}, so med=m⋅(mλ(n))h≡m⋅1h=m(modn)m^{ed} = m\cdot(m^{\lambda(n)})^{h}\equiv m\cdot1^h = m \pmod n (proof on slide 51).

Key Generation of RSA Cryptosystem {Exam Q5}

  1. Choose two large primes pp and qq, preferably between 210232^{1023} and 210242^{1024}. They are kept secret.
  2. Compute the modulus n=pqn=pq. Use nn as part of the public key.
  3. Compute Carmichael's totient function λ(n)=lcm(λ(p),λ(q))=lcm(p−1,q−1)\lambda(n)=\text{lcm}(\lambda(p),\lambda(q))=\text{lcm}(p-1,q-1). Keep λ(n)\lambda(n) secret.
  4. Choose a coprime ee with λ(n)\lambda(n). Use ee as part of the public key.
  5. Compute dd in the equation ed % λ(n)=1ed\,\%\,\lambda(n)=1 by solving λ(n)k+ed=1\lambda(n)k+ed=1 via the extended Euclid's method. Use dd as the private key.
  6. The public key is (n,e)(n,e), while the private key is dd.

ed≡1(modλ(n)),public (n,e),private d\boxed{ed\equiv1\pmod{\lambda(n)},\qquad \text{public }(n,e),\quad \text{private } d}

Demonstration

  1. Choose two primes p=17p=17 and q=11q=11.
  2. Compute the modulus n=17×11=187n=17\times11=187.
  3. Compute Carmichael's totient λ(n)=lcm(17−1,11−1)=lcm(16,10)=80\lambda(n)=\text{lcm}(17-1,11-1)=\text{lcm}(16,10)=80.
  4. Choose e=7e=7, coprime with λ(n)\lambda(n).
  5. Solve λ(n)⋅k+ed=1\lambda(n)\cdot k+ed=1 for dd:

egcd(80,1,0 ∣ 7,0,1)=  egcd(7,0,1 ∣ 3,1,−11)=  egcd(3,1,−11 ∣ 1,−2,23)=  egcd(1,−2,23 ∣ 0,5,−80)=  (1,−2,23)⇒(g,k,d)\begin{aligned}&\text{egcd}(80,1,0\,|\,7,0,1)\\=\;&\text{egcd}(7,0,1\,|\,3,1,-11)\\=\;&\text{egcd}(3,1,-11\,|\,1,-2,23)\\=\;&\text{egcd}(1,-2,23\,|\,0,5,-80)\\=\;&(1,-2,23)\Rightarrow(g,k,d)\end{aligned}

  • (The slide's first line prints "7,1,07,1,0". The correct start is 7,0,17,0,1, as in slide 42.)
  • Check: 80×(−2)+7×23=−160+161=180\times(-2)+7\times23 = -160+161 = 1 ✓
  1. The public key is (n=187, e=7)(n=187,\,e=7), while the private key is d=23d=23.

🎙️ 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 rr — we can guess rr by quantum algorithms."
❓ Why does knowing p,qp,q break everything? With p,qp,q the attacker computes λ(n)=lcm(p−1,q−1)\lambda(n)=\text{lcm}(p-1,q-1), then runs the same extended Euclid to get dd from the public ee. So factoring nn = stealing the private key.

Proof of Correctness

  1. The starting point is λ(pq)=lcm(p−1,q−1)\lambda(pq)=\text{lcm}(p-1,q-1)
  2. Since ed % λ(pq)=1ed\,\%\,\lambda(pq)=1, ed−1ed-1 is a multiple of lcm(p−1,q−1)\text{lcm}(p-1,q-1). So ed−1ed-1 is divisible by both p−1p-1 and q−1q-1:

ed−1=h1(p−1)=h2(q−1)for some integers h1,h2>0ed-1 = h_1(p-1) = h_2(q-1)\quad\text{for some integers } h_1,h_2>0

  1. Since (med)%pq=m%pq(m^{ed})\%pq = m\%pq, we can prove (med)%p=m%p(m^{ed})\%p=m\%p and (med)%q=m%q(m^{ed})\%q = m\%q separately. Both parts are analogous.
  2. The pp part:
    • Case 1 (m%p=0m\%p=0): mm is a multiple of pp, so medm^{ed} is also a multiple of pp. Thus med%p=m%p=0m^{ed}\%p=m\%p=0.
    • Case 2 (m%p≠0m\%p\neq0): med=mh1(p−1)+1=m×m(p−1)h1m^{ed}=m^{h_1(p-1)+1}=m\times m^{(p-1)h_1}. By Fermat's little theorem, m×(m(p−1))h1%p=m×1h1=mm\times(m^{(p-1)})^{h_1}\%p = m\times1^{h_1}=m.
  3. The proof of the qq part is analogous to that of the pp part.
  4. Therefore:

(med) % pq=m % pq\boxed{(m^{ed})\,\%\,pq = m\,\%\,pq}

🎙️ 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

  1. Suppose we choose two primes p=23p=23 and q=17q=17. Generate the public key (n,e)(n,e) and the private key dd.
  2. Discuss why it is intractable to factorize a large number nn directly into two multiplicands pp and qq, although we know that both are large primes.
  3. Discuss why the Fermat–Euler theorem makes it easier to factorize a large number that is a product of two large primes.
  4. Explain why Fermat's little theorem plays a crucial role in the RSA cryptosystem. [Hint: consult its proof of correctness.]
  5. 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 encode(c0c1…c7)=∑k=072k×ord(ck)\text{encode}(c_0c_1\dots c_7)=\sum_{k=0}^{7}2^k\times\text{ord}(c_k). The system should randomize pp and qq, and generate (n,e)(n,e) and dd accordingly.
  • Worked hint for Q1: n=391n=391, λ=lcm(22,16)=176\lambda=\text{lcm}(22,16)=176. Pick e=3e=3 (coprime with 176). Solve 3d≡1(mod176)3d\equiv1\pmod{176}: d=59d=59 (since 3×59=177=176+13\times59=177=176+1). Public (391,3)(391,3), private 5959.

Shor's Algorithm {Exam Q5}

  • Shor's algorithm is a classical–quantum hybrid method for factorizing n=pqn=pq, where pp and qq are large prime factors
  • Hybrid algorithm: factorize nn
    1. If n=1n=1, then nn is a factor.
    2. Otherwise, pick a random prime aa, where 1<a<N1<a<\sqrt N.
    3. Compute the greatest common divisor k=gcd⁡(n,a)k=\gcd(n,a).
    4. If k≠1k\neq1, then we have found a factor. Carry on with factorizing kk and n/kn/k recursively.
    5. Otherwise, compute the order r≈ϕ(n)r\approx\phi(n) using quantum phase estimation.
    6. If rr is odd, go back to Step 2.
    7. Otherwise, compute g=gcd⁡(n, ar/2+1)g=\gcd(n,\,a^{r/2}+1).
    8. If g=1g=1, go back to Step 2.
    9. Otherwise, we have found a factor. Carry on with factorizing gg and n/gn/g recursively.
  • Figure 19: flowchart. "Guess factor aa of nn" → "aa divides nn?"
    • Y → "Factorize aa and n/an/a (recursive)"
    • N → "Compute order r=ϕ(n)r=\phi(n) using quantum phase estimation" (with the clock icon) → "rr is odd?"
      • Y → back to Guess
      • N → "ar/2+1a^{r/2}+1 divides nn?"
        • N → back to Guess
        • Y → "Compute GCD g=gcd⁡(n,ar/2+1)g=\gcd(n,a^{r/2}+1)" → "Factorize gg and n/gn/g (recursive)"
  • Time complexity is O(L2log⁡L)O(L^2\log L), where LL is the length of the bitstring nn

Shor: O(L2log⁡L)vs classical guessing: O(2LL2)\boxed{\text{Shor: } O(L^2\log L)\quad\text{vs classical guessing: } O(2^LL^2)}

🎙️ 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, rr."
🎙️ In class (Nov 3-02, 50:56–51:58): "If rr is odd, go back. It means you cannot solve it. If it's even, compute the GCD of nn and ar/2+1a^{r/2}+1. 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 gg on one branch and n/gn/g 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 N2N^2" in the number itself. Here it is L2log⁡LL^2\log L, "where LL 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 aa: we need an "engine" to rotate. Any aa coprime with nn gives a periodic sequence ax mod na^x\bmod n. Random choice makes a good aa (even rr, no trivial GCD) likely: at least 50% per try.
  • Steps 3–4, GCD first: it is cheap (Euclid, O(L2)O(L^2)). If aa already shares a factor with nn, we are done without any quantum work.
  • Step 5, order via QPE: finding rr classically means computing a1,a2,…a^1,a^2,\dots until 1 appears, which takes up to ∼n\sim n steps (exponential in LL). QPE reads the rotation frequency in polynomial time. This is the only quantum step.
  • Step 6, rr odd → retry: the difference-of-squares split (ar/2−1)(ar/2+1)(a^{r/2}-1)(a^{r/2}+1) needs an integer r/2r/2.
  • Steps 7–8, g=1g=1 → retry: the brackets may contain no useful factor. This happens when ar/2≡−1(modn)a^{r/2}\equiv-1\pmod n, where all of nn hides in one bracket. Then you need a new aa.
  • Step 9, recursion: gg and n/gn/g may still be composite (e.g. 152=23⋅19152=2^3\cdot19), 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 rr). Once you know the rhythm, simple arithmetic (GCD) tells you the combination. The quantum computer is only the stethoscope.

Worked toy example: factor n=15n=15 (not on the slides; for understanding)

  • Pick a=7a=7. gcd⁡(7,15)=1\gcd(7,15)=1, so go to the quantum step.
  • Powers of 7 mod 15: 71=77^1=7, 72=49%15=47^2=49\%15=4, 73=28%15=137^3=28\%15=13, 74=91%15=17^4=91\%15=1. So the order is r=4r=4 (the sequence 1, 7, 4, 13, 1, 7, … has period 4).
  • r=4r=4 is even, so ar/2=72=49a^{r/2}=7^2=49:
    • gcd⁡(49+1,15)=gcd⁡(50,15)=5\gcd(49+1,15)=\gcd(50,15)=5 ✓
    • gcd⁡(49−1,15)=gcd⁡(48,15)=3\gcd(49-1,15)=\gcd(48,15)=3 ✓
  • 15=3×515=3\times5 🎉
  • What QPE actually returns (with L=3L=3 counting qubits, 23=82^3=8 bars): the phases are m/r∈{0,14,12,34}m/r\in\{0,\tfrac14,\tfrac12,\tfrac34\}, so peaks at k∗∈{0,2,4,6}k^*\in\{0,2,4,6\}.
measured k∗k^*k∗/8k^*/8fractiondenominatoroutcome
000/10/11no info → run again
20.251/41/44r=4r=4 ✓
40.51/21/22only a divisor of rr (72%15=4≠17^2\%15=4\neq1) → combine runs
60.753/43/44r=4r=4 ✓
  • Two runs giving denominators 2 and 4 → lcm(2,4)=4=r\text{lcm}(2,4)=4=r. This is why the LCM step exists.

Estimating the Order with Quantum Phase Estimation {Exam Q5}

  • Motivation: modulo nn with order rr can be seen as a full rotation within rr steps (the slide writes "nrnr steps")
  • We can define a unitary operator U%n(a)\mathbf U_{\%n}(a) for modulo nn as the mapping

U%n: ∣BL(x)⟩↦∣BL(ax%n)⟩\boxed{\mathbf U_{\%n}:\ |\mathbb B_L(x)\rangle\mapsto|\mathbb B_L(a^x\%n)\rangle}

  • Recall that nn is the public key and aa is obtained from guessing
  • Precise definition:

U%n(a)=∑k=02L−1∣BL(ak%n)⟩⟨BL(k)∣\boxed{\mathbf U_{\%n}(a) = \sum_{k=0}^{2^L-1}|\mathbb B_L(a^k\%n)\rangle\langle\mathbb B_L(k)|}

  • Apply quantum phase estimation to U%n(a)\mathbf U_{\%n}(a) to approximate its phase θ\theta:

θ=QPE(U%n(a))\theta = \text{QPE}(\mathbf U_{\%n}(a))

  • Since θ\theta is actually a fraction k∗/2Lk^*/2^L, where k∗k^* is the optimal phase index, we still have to approximate the order rr from

k∗2L≈mrwhere 0<m<r are coprime\boxed{\frac{k^*}{2^L}\approx\frac mr}\qquad\text{where } 0<m<r \text{ are coprime}

  • The approximation by a coprime fraction is called the continued fraction method

📝 Instructor's annotation: wrote "U%n\mathbf U_{\%n} :" 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 kk, the output is kk modulo nn. I recompute the index, make it a circle." Example: the modulo-7 operator maps ∣10⟩↦∣3⟩|10\rangle\mapsto|3\rangle. "When you apply QPE, you start to see the rotation."
🎙️ In class (Nov 3-02, 55:11): "Your phase θ\theta has the form k∗k^* over 2 to the number of qubits. You approximate it as a fraction m/rm/r 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 Ua∣x⟩=∣a⋅x mod n⟩\mathbf U_a|x\rangle=|a\cdot x\bmod n\rangle.

  • It is unitary, because aa is coprime with nn, so it just permutes 0,…,n−10,\dots,n-1.
  • Starting from ∣1⟩|1\rangle, applying it kk times gives ∣ak mod n⟩|a^k\bmod n\rangle. That is the slide's ak%na^k\%n.
  • The controlled powers Ua2j\mathbf U_a^{2^j} are made by multiplying by a2j mod na^{2^j}\bmod n, computed classically by repeated squaring (a→a2→a4→…a\to a^2\to a^4\to\dots, each mod nn). In the code: factor = np.mod(np.power(a, power), n) with power = 2**k.
  • So the expensive U512\mathbf U^{512} problem from QPE disappears here: Ua512=Ua512 mod n\mathbf U_a^{512}=\mathbf U_{a^{512}\bmod n} is one multiplication.
    ❓ Why are the phases m/rm/r? Ua\mathbf U_a cycles 1→a→a2→⋯→ar−1→11\to a\to a^2\to\dots\to a^{r-1}\to1, a clock with rr ticks. Its eigenvectors ∣um⟩=1r∑k=0r−1cis(−2πmk/r)∣ak mod n⟩|u_m\rangle=\frac1{\sqrt r}\sum_{k=0}^{r-1}\text{cis}(-2\pi mk/r)|a^k\bmod n\rangle have eigenvalues cis(2πm/r)\text{cis}(2\pi m/r). So θ=m/r\theta=m/r for some m∈{0,…,r−1}m\in\{0,\dots,r-1\}.
    ❓ Why don't we need to know the eigenvector? ∣1⟩=1r∑m∣um⟩|1\rangle=\frac1{\sqrt r}\sum_m|u_m\rangle is an equal mix of all eigenvectors. Starting the target in ∣1⟩|1\rangle makes QPE return a random m/rm/r, which is fine, because the denominator is still rr.
    ⚠️ Code note: the PennyLane code (slide 60) starts the target in ∣0…0⟩|0\dots0\rangle. Since a⋅0=0a\cdot0=0, that state is a fixed point (phase 0), so QPE returns k∗=0k^*=0 and r=1r=1. The quantum branch then never fires, and 152 is factored by the classical GCD branch. Textbook Shor initialises the target register to ∣1⟩|1\rangle.

Continued Fraction Method {Exam Q5}

  • A continued fraction is a rational estimate of a real number:

x≈a0+1a1+1a2+1a3+⋱=[a0∣a1,a2,a3,… ]a0,a1,a2,⋯∈Z\boxed{x\approx a_0+\cfrac{1}{a_1+\cfrac{1}{a_2+\cfrac{1}{a_3+\ddots}}} = [a_0|a_1,a_2,a_3,\dots]}\qquad a_0,a_1,a_2,\dots\in\mathbb Z

  • Continued fraction method:
    1. Start with index i=0i=0 and q0=xq_0=x.
    2. Let ai=⌊qi⌋a_i=\lfloor q_i\rfloor.
    3. If qi=aiq_i=a_i or ii hits the limit, then stop.
    4. Otherwise, compute qi+1=1/(qi−ai)q_{i+1}=1/(q_i-a_i).
    5. Increase i=i+1i=i+1.
    6. Go to step 2.
  • Example: approximate 1.23456 with a limit of 3:
iiqiq_iaia_i
01.234561
14.263304
23.797933
31.253241
  • This gives three convergents:

[1∣4]=1+1/4=54=a1b1[1|4] = 1+1/4 = \frac54 = \frac{a_1}{b_1}

[1∣4,3]=1+14+1/3=1613=a2b2[1|4,3] = 1+\frac{1}{4+1/3} = \frac{16}{13} = \frac{a_2}{b_2}

[1∣4,3,1]=1+14+13+1/1=2117=a3b3[1|4,3,1] = 1+\frac{1}{4+\frac{1}{3+1/1}} = \frac{21}{17} = \frac{a_3}{b_3}

📝 Instructor's annotation: labelled the three results a1b1,a2b2,a3b3\frac{a_1}{b_1},\frac{a_2}{b_2},\frac{a_3}{b_3} (numerators aka_k, denominators bkb_k), ready for the next slide.
🎙️ In class (Nov 3-02, 57:09–59:58): "Floor it, you've got a0a_0. Take the 0.23456, inverse it, you've got q1q_1. 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 k∗/2Lk^*/2^L (e.g. 0.75 = 6/8). But rr is generally not a power of 2. Continued fractions find the simplest fraction (smallest denominator) that is very close to k∗/2Lk^*/2^L. Theory guarantees that if 2L≳n22^L\gtrsim n^2, the true m/rm/r appears among the convergents, and its denominator is the candidate rr.
💡 Analogy: Recognising 3.14159…3.14159\ldots 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 k∗/2Lk^*/2^L from quantum phase estimation on U%n(a)\mathbf U_{\%n}(a):

k∗2L=QPE(U%n(a))\frac{k^*}{2^L} = \text{QPE}(\mathbf U_{\%n}(a))

  • Extract KK convergents of k∗/2Lk^*/2^L via the continued fraction method:

k∗2L≈a1b1,a2b2,a3b3,…,aKbK\frac{k^*}{2^L}\approx\frac{a_1}{b_1},\frac{a_2}{b_2},\frac{a_3}{b_3},\dots,\frac{a_K}{b_K}

  • We may now treat each bkb_k as a candidate for the order rr
  • In the original Shor's algorithm, we compute the least common multiple of b1,…,bKb_1,\dots,b_K and use it as the candidate order instead:

r=lcm(b1,b2,b3,…,bK)\boxed{r = \text{lcm}(b_1,b_2,b_3,\dots,b_K)}

  • Using the LCM guarantees that we will have a large approximation r≈ϕ(n)r\approx\phi(n)
  • In practice, we can do this automatically by converting k∗/2Nk^*/2^N 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 rr, the order, the frequency of rotation. And that is Shor's algorithm."
❓ Why LCM? If the measured mm shares a factor with rr (e.g. m/r=2/4m/r=2/4 shows up as 1/21/2), the denominator is only a divisor of rr. The LCM of several denominators rebuilds the full rr (or a multiple of it, which still satisfies ar≡1a^r\equiv1).
⚠️ Failure cases of the quantum part:

  • k∗=0k^*=0 gives no information
  • a reduced fraction gives a too-small rr
  • too few counting qubits, or noise, give a wrong convergent
  • Always check classically that ar%n=1a^r\%n=1. 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 gcd⁡(n,ar/2−1)\gcd(n, a^{r/2}-1), while the slide algorithm tests ar/2+1a^{r/2}+1. 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_matrix builds a permutation matrix: ∣x⟩↦∣apowerx mod n⟩|x\rangle\mapsto|a^{\text{power}}x\bmod n\rangle for x<nx<n, and identity for x≥nx\ge n. 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 = ∣+⟩⊗N|+\rangle^{\otimes N}; apply_power_modulo(... 2**k ...) = CU2k\mathbf{CU}^{2^k}; adjoint(QFT) = InvQFT; argmax = k∗k^*; Fraction(...).denominator = continued fractions.

Exercise 6.7: Shor's Algorithm

  1. Identify the differences between the classical factorization method and Shor's algorithm.
  2. Discuss why knowing the order r≈ϕ(n)r\approx\phi(n) helps speed up classical factorization.
  3. Explain why the algorithm resorts to classical factorization when rr is odd. Hint: consult the Fermat–Euler theorem.
  4. Consider the unitary operator U%n(a)=∑k=02L−1∣BL(ak%n)⟩⟨BL(k)∣\mathbf U_{\%n}(a)=\sum_{k=0}^{2^L-1}|\mathbb B_L(a^k\%n)\rangle\langle\mathbb B_L(k)|. Explain why applying this operator on ∣+⟩⊗L|+\rangle^{\otimes L} is equivalent to 2L2^L rotations.
  5. Explain why the phase θ\theta extracted with quantum phase estimation has to be approximated by a fraction m/rm/r, where mm and rr are coprime, instead of k∗/2Lk^*/2^L.
  • Answer sketches (these are exactly the "why" questions to expect):
    • Q1: classical = blind guessing of aa until gcd⁡≠1\gcd\neq1 (exponential). Shor = same loop, but on a miss it uses QPE to get the order rr and builds the factor gcd⁡(ar/2±1,n)\gcd(a^{r/2}\pm1,n) (polynomial, O(L2log⁡L)O(L^2\log L)).
    • Q2: ar≡1(modn)⇒n ∣ (ar/2−1)(ar/2+1)a^r\equiv1\pmod n \Rightarrow n\,|\,(a^{r/2}-1)(a^{r/2}+1), so one GCD gives a factor directly.
    • Q3: odd rr means r/2r/2 is not an integer, so no difference-of-squares split. Choose a new aa.
    • Q4: the ∣+⟩⊗L|+\rangle^{\otimes L} controls select every power k=0..2L−1k=0..2^L-1 at once (rotate or not per bit), so all 2L2^L rotation counts happen in superposition.
    • Q5: 2L2^L is a power of 2, but rr is arbitrary. k∗/2Lk^*/2^L is only a binary approximation of m/rm/r. The continued fraction recovers the exact simple fraction, whose denominator is rr (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 {0,1}m↦{0,1}n\{0,1\}^m\mapsto\{0,1\}^n, where m≤nm\le n
  • A function ff is NOT one-to-one if and only if for all x,x′\mathbf x,\mathbf x' there is a non-zero solution s\mathbf s such that

f(x)=f(x′)  and  x′=x⊕s\boxed{f(\mathbf x)=f(\mathbf x')\ \text{ and }\ \mathbf x'=\mathbf x\oplus\mathbf s}

  • In classical computing it is intractable to check this condition on all possible pairs x,x′\mathbf x,\mathbf x', due to the O(2N/2)O(2^{N/2}) time complexity
  • Quantum solution: test all input strings x\mathbf x at the same time and observe the distribution of the outputs f(x)f(\mathbf x)
  • 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 ff is one-to-one
  • Force ff to an extreme, where it generates an output hash code of the same length as the input
  • Convert ff into a quantum operator Uf\mathbf U_f that maps

∣x1:L⟩⊗∣0⟩⊗L↦∣x1:L⟩⊗∣f(x1:L)⟩\boxed{|x_{1:L}\rangle\otimes|0\rangle^{\otimes L}\mapsto|x_{1:L}\rangle\otimes|f(x_{1:L})\rangle}

  • Basic idea: enumerate all possible inputs x\mathbf x and solutions s\mathbf s of ff, and measure the distribution of all output hash codes
  • First, enumerate all possible inputs kk:

∣q1⟩=Uf[(H⊗L∣0⟩⊗L)⊗∣0⟩⊗L]=12L/2∑k=02L−1∣BL(k)⟩⊗∣f(BL(k))⟩|q_1\rangle = \mathbf U_f\big[(\mathbf H^{\otimes L}|0\rangle^{\otimes L})\otimes|0\rangle^{\otimes L}\big] = \frac{1}{2^{L/2}}\sum_{k=0}^{2^L-1}|\mathbb B_L(k)\rangle\otimes|f(\mathbb B_L(k))\rangle

  • Then enumerate all solutions ss:

∣q2⟩=[H⊗L⊗I⊗L]∣q1⟩=12L/2∑k=02L−1(∑s=02L−1(−1)s⋅k2L/2∣BL(s)⟩)⊗∣f(BL(k))⟩=∑s=02L−1∑k=02L−1(−1)s⋅k2L∣BL(s)⟩⊗∣f(BL(k))⟩|q_2\rangle = [\mathbf H^{\otimes L}\otimes\mathbf I^{\otimes L}]|q_1\rangle = \frac{1}{2^{L/2}}\sum_{k=0}^{2^L-1}\left(\sum_{s=0}^{2^L-1}\frac{(-1)^{s\cdot k}}{2^{L/2}}|\mathbb B_L(s)\rangle\right)\otimes|f(\mathbb B_L(k))\rangle = \sum_{s=0}^{2^L-1}\sum_{k=0}^{2^L-1}\frac{(-1)^{s\cdot k}}{2^L}|\mathbb B_L(s)\rangle\otimes|f(\mathbb B_L(k))\rangle

📝 Instructor's annotation: labelled ∣f(x1:L)⟩|f(x_{1:L})\rangle as "hash".
🎙️ In class (Nov 3-03, 21:25–21:43): s⋅ks\cdot k is the binary dot product (bitwise AND, then XOR/parity).

Simon's Algorithm (cont'd)

  • By the phase kickback technique:

∣q2⟩=∑s=02L−1∑k=02L−1(−1)s⋅k2L∣BL(s)⟩⊗∣f(BL(k))⟩=∑s=02L−1[∣BL(s)⟩⊗∑k=02L−1(−1)s⋅k2L∣f(BL(k))⟩]|q_2\rangle = \sum_{s=0}^{2^L-1}\sum_{k=0}^{2^L-1}\frac{(-1)^{s\cdot k}}{2^L}|\mathbb B_L(s)\rangle\otimes|f(\mathbb B_L(k))\rangle = \sum_{s=0}^{2^L-1}\left[|\mathbb B_L(s)\rangle\otimes\sum_{k=0}^{2^L-1}\frac{(-1)^{s\cdot k}}{2^L}|f(\mathbb B_L(k))\rangle\right]

  • The probability of solution ss is therefore

Poracle(s)=∣∑k=02L−1(−1)s⋅k2L∣f(BL(k))⟩∣2P_{\text{oracle}}(s) = \left|\sum_{k=0}^{2^L-1}\frac{(-1)^{s\cdot k}}{2^L}|f(\mathbb B_L(k))\rangle\right|^2

  • Case 1: if ff is one-to-one, the probability distribution of all solutions ss is uniform:

Poracle(s)=1/2L\boxed{P_{\text{oracle}}(s)=1/2^L}

  • Case 2: if ff is many-to-one (i.e. non-zero oracle), the probability distribution of all solutions jj is not uniform
    • If ss is the solution, the range of f(s)f(s) will be smaller than 2L2^L due to the many-to-one mapping
    • We deduce the mapping X={x1,…,xN}X=\{x_1,\dots,x_N\} to their common image yy by

Poracle(s)=∣X∣/2LP_{\text{oracle}}(s)=|X|/2^L

🎙️ 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 ∣x1⟩…∣xn⟩|x_1\rangle\dots|x_n\rangle → H each → Uf\mathbf U_f → H each. Output wires ∣01⟩…∣0n⟩|0_1\rangle\dots|0_n\rangle → Uf\mathbf U_f → 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 ff, we discard ∣0⟩⊗L|0\rangle^{\otimes L} and ∣1⟩⊗L|1\rangle^{\otimes L} due to the lack of information
  • Choose the most likely image (i.e. the highest probability) and its linearly independent counterparts y1,…,yL−1\mathbf y_1,\dots,\mathbf y_{L-1}
  • Solve for the solution s=[s1…sL]⊤\mathbf s=[s_1\dots s_L]^\top from a simple XOR equation system:

y1,1s1⊕⋯⊕y1,LsL=0  ⋮yL−1,1s1⊕⋯⊕yL−1,LsL=0\begin{aligned}y_{1,1}s_1\oplus\dots\oplus y_{1,L}s_L &= 0\\ &\ \,\vdots\\ y_{L-1,1}s_1\oplus\dots\oplus y_{L-1,L}s_L &= 0\end{aligned}

  • If there is a non-zero solution, we select it as the solution s\mathbf s
  • Example (from the code above):
    • Discard 0000 and 1111 due to no info
    • Select 1000, 0111, and 0100
    • Solve for s\mathbf s:

(1⋅s1)⊕(0⋅s2)⊕(0⋅s3)⊕(0⋅s4)=0(0⋅s1)⊕(1⋅s2)⊕(1⋅s3)⊕(1⋅s4)=0(0⋅s1)⊕(1⋅s2)⊕(0⋅s3)⊕(0⋅s4)=0\begin{aligned}(1\cdot s_1)\oplus(0\cdot s_2)\oplus(0\cdot s_3)\oplus(0\cdot s_4)&=0\\(0\cdot s_1)\oplus(1\cdot s_2)\oplus(1\cdot s_3)\oplus(1\cdot s_4)&=0\\(0\cdot s_1)\oplus(1\cdot s_2)\oplus(0\cdot s_3)\oplus(0\cdot s_4)&=0\end{aligned}

  • This gives s1=0s_1=0, s2=0s_2=0, and s3=s4s_3=s_4, so [0,0,0,0]⊤[0,0,0,0]^\top or [0,0,1,1]⊤[0,0,1,1]^\top
  • The non-zero solution s=[0,0,1,1]⊤\mathbf s=[0,0,1,1]^\top 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.
    1. ∣x1,x2⟩↦∣x2,x1⟩|x_1,x_2\rangle\mapsto|x_2,x_1\rangle
    2. ∣x1,x2⟩↦∣x1,x2⟩|x_1,x_2\rangle\mapsto|x_1,x_2\rangle
    3. ∣x1,x2,x3⟩↦∣x3,x1,x1∧x2⟩|x_1,x_2,x_3\rangle\mapsto|x_3,x_1,x_1\wedge x_2\rangle
    4. ∣x1,x2,x3⟩↦∣x1∧x2,x1∨x3,x2∧x3⟩|x_1,x_2,x_3\rangle\mapsto|x_1\wedge x_2,x_1\vee x_3,x_2\wedge x_3\rangle
    5. ∣x1,x2,x3,x4⟩↦∣x4,x3,x2,x1⟩|x_1,x_2,x_3,x_4\rangle\mapsto|x_4,x_3,x_2,x_1\rangle
    6. ∣x1,x2,x3,x4⟩↦∣x1⊕x2,x2⊕x3,x3⊕x4,x4⊕x1⟩|x_1,x_2,x_3,x_4\rangle\mapsto|x_1\oplus x_2,x_2\oplus x_3,x_3\oplus x_4,x_4\oplus x_1\rangle
    7. ∣x1,x2,x3,x4⟩↦∣x1∨x2,x1∧x3,x2∨x3,x2∧x4⟩|x_1,x_2,x_3,x_4\rangle\mapsto|x_1\vee x_2,x_1\wedge x_3,x_2\vee x_3,x_2\wedge x_4\rangle
  • 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 ff 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 x,x′\mathbf x,\mathbf x' for any function ff, resulting in O(2N/2)O(2^{N/2}) 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 2L2^L 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 U%n(a,k)=∑k=02L−1∣ak%n⟩⟨k∣\mathbf U_{\%n}(a,k)=\sum_{k=0}^{2^L-1}|a^k\%n\rangle\langle k|
  • 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 nn. Once you've got rr from QPE, compute ar/2+1a^{r/2}+1 and try dividing it into nn. 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
    1. Explain the limitation of classical unstructured search (O(n)O(n)) and how Grover's algorithm provides a quadratic speedup (O(n)O(\sqrt n)).
    2. Describe the two core components of the Grover iteration: the oracle function for sign-flipping the solution, and the diffusion operator for amplitude amplification.
    3. Calculate the optimal number of iterations to avoid overshooting the solution.
    4. Implement a quantum search routine in PennyLane using qml.FlipSign and qml.templates.GroverOperator.
  • Quantum Fourier Transform (QFT)
    1. Differentiate between the classical Fast Fourier Transform and the Quantum Fourier Transform in terms of input representation and time complexity.
    2. Construct the QFT circuit using Fourier blocks composed of Hadamard gates and conditional dyadic rational phase gates.
    3. Apply the Inverse Quantum Fourier Transform to map frequency-domain vectors back to the time domain.
  • Quantum Phase Estimation (QPE)
    1. Define the concept of a global phase and explain how QPE extracts the phase of a unitary operator given an eigenvector.
    2. Illustrate the QPE workflow: creating a superposition on estimation qubits, applying controlled-power unitary gates, and decoding via InvQFT.
    3. Identify practical strategies for large-scale QPE, such as Trotterization or diagonalization of the operator.
  • Shor's Algorithm
    1. Contrast classical prime factorization with the quantum-enhanced speedup.
    2. Describe the hybrid nature of Shor's algorithm, specifically how it uses QPE to solve the order-finding problem.
    3. 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
    1. Formulate Simon's problem as the task of determining whether a hash function is one-to-one or many-to-one.
    2. Execute the quantum procedure to find the period by measuring output distributions and solving a system of XOR equations.
    3. Evaluate the security implications of hash collisions in cryptographic systems.