Shor's algorithm
For this Qiskit in Classrooms module, students must have a working Python environment with the following packages installed:
qiskitv2.1.0 or newerqiskit-ibm-runtimev0.40.1 or newerqiskit-aerv0.17.0 or newerqiskit.visualizationnumpypylatexenc
To set up and install the packages above, see the Install Qiskit guide. In order to run jobs on real quantum computers, students will need to set up an account with IBM Quantum® by following the steps in the Set up your IBM Cloud account guide.
This module was tested and used three seconds of QPU time. This is an estimate only. Your actual usage may vary.
# Uncomment and modify this line as needed to install dependencies
#!pip install 'qiskit>=2.1.0' 'qiskit-ibm-runtime>=0.40.1' 'qiskit-aer>=0.17.0' 'numpy' 'pylatexenc'
Intro
In the early 1990s, there was growing excitement around the potential of quantum computers to solve problems that were hard for classical computers. A few talented computer scientists had devised algorithms that demonstrated the power of quantum computing for some niche, contrived problems, but nobody had found a single, "killer app" of quantum computing that was sure to revolutionize the field. That was, until 1994, when Peter Shor came up with what is now called Shor's algorithm for factoring large numbers.
It was well known at the time that finding the prime factors of a large number was extremely difficult for a classical computer. In fact, internet security protocols relied on this difficulty. Shor found a way to find these factors exponentially more efficiently by offloading some of the more challenging steps onto a theoretical, future quantum computer.
In this module, we will explore Shor's algorithm. First, we'll give a bit more context to the algorithm, formalizing the problem it solves and explaining the relevance to cyber security. Next, we'll give a primer on modular mathematics and how to apply it to the factoring problem, showing how factoring reduces to another problem called "order-finding." We'll show how the Quantum Fourier Transform and Quantum Phase Estimation that we learned about in a previous module come into play, and how to use them to solve the order-finding problem.
Finally, we'll run Shor's algorithm on a real quantum computer! Keep in mind, though, that this algorithm will really only be useful when we have a large, fault-tolerant quantum computer, which is still some years away. So, we'll just factor a small number to demonstrate how the algorithm works.
The factoring problem
The goal of the factoring problem is to find the prime factors of a number . For some numbers , this is pretty easy. For example, if is even, one of its prime factors will be 2. If is a prime power, meaning for some prime number , it is also fairly easy to find : we just approximate the root of and look for nearby primes that could be .
Where classical computers struggle, though, is when is odd and not a prime power. This is the case Shor's algorithm deals with. The algorithm finds two factors and such that . It can be applied recursively until all factors are prime. In the next sections we'll see how this problem is tackled.
Relevance to cyber security
Many cryptographic schemes have been built based on the fact that factoring large numbers is hard, including one that is commonly used today, called RSA. In RSA, a public key is created by multiplying two large prime numbers together to get . Then, anyone can use this public key to encrypt data. But only somebody with the private key, and , can decrypt that data.
If were easy to factor, then anyone would be able to determine what and are and break the encryption. But it's not. This is a famously difficult problem. In fact, the prime factors of a number called RSA1024, which is 1024 binary digits and 309 decimal digits long, has still not been found, despite a $100,000 prize being offered for its factoring way back in 1991.
Shor's solution
In 1994, Peter Shor realized that a quantum computer could factor a large number exponentially more efficiently than a classical computer could. His insight relied on the relationship between this factoring problem and modular arithmetic. We'll go through a brief primer on modular arithmetic, then we'll see how we can use this to factor .
Modular arithmetic
Modular arithmetic is a system of counting that is cyclic, meaning that while counting starts in the usual way, with integers 0, 1, 2, etc., at some point, after a period , the counting starts over again. Let's see how this works with an example. Say our period is 5. Then, as we're counting, where we would normally hit 5, we instead start over at 0:
This is because in the "modulo-5" world, 5 is equivalent to 0. We say that . In fact, all multiples of 5 will be equivalent to .
Check your understanding
Read the question(s) below, think about your answer, then click the triangle to reveal the solution.
Use modular arithmetic to solve the following problem:
You depart on a long, transcontinental train ride at 8 AM. The train ride is 60 hours long. What time is it when you arrive?
Answer:
The period is 24, since there are 24 hours in a day. So, this problem can be written in modular arithmetic as:
So, you would arrive at your destination at 20:00, or 8 PM.
and
It's often useful to introduce two sets, and . is simply the set of numbers that exist in a "modulo-" world. For example, when we were counting modulo-5, the set would be . Another example: . We can perform addition and multiplication (modulo ) on the elements in , and the result of each of these operations also is an element in , making a mathematical object called a ring.
There's a special subset of that is of particular interest to us for Shor's algorithm. That is the subset of numbers in such that the greatest common divisor between each element and is 1, so each element is "co-prime" to . If we take the set of these numbers along with the modular multiplication operation, then this forms another mathematical object, called a group. We call this group . Turns out that with (and finite groups in general), if we pick any element , and repeatedly multiply to itself, we'll always eventually get the number . The minimum number of times one must multiply to itself in order to get is called the order of . This fact will be very important to our discussion of how to factor numbers below.
Check your understanding
Read the question(s) below, think about your answer, then click the triangle to reveal the solution.
What is ?
Answer:
We excluded the following numbers:
What is the order of each of the elements in ?
Answer:
The order is the lowest number such that for each element .
Note that, while we were able to find the order of the numbers in , this is NOT an easy task in general, for larger . This is the crux of the factoring problem and why we need a quantum computer. We'll see why as we work through the rest of the notebook.
Apply modular arithmetic to the factoring problem
The key to finding factors and such that comes down to finding some other integer such that
and
How does finding help us find the factors and ? Let's go through the argument now. Since , that means that . In other words, is a multiple of . So, for some integer ,
We can factor to get:
From our initial assumptions we know that , so doesn't divide evenly into either or . So, the two factors of , and must each divide into and . Either is a factor of and is a factor of , or vice versa. Therefore, if we compute the greatest common divisors (GCDs) between and both and , that will give us the factors and . Calculating the GCD between two numbers is a classically easy task that can be accomplished, for example, using Euclid's algorithm.
Check your understanding
Read the question(s) below, think about your answer, then click the triangle to reveal the solution.
It might be tricky to understand each step of logic above, so try working through it with an example. Use and . First, verify that and . Then continue to verify each step. Finally, calculate and verify that they are the factors of .
Answer:
, which is , so .
, which is not equivalent to .
, which is not equivalent to .
Now, we know that for some integer . This is verified when we plug in and : when .
Now, we need to calculate and .
So, we found our factors of !
The algorithm
Now that we've seen how finding some integer such that helps us to factor , we can go through Shor's algorithm. It essentially boils down to finding :
- Pick a random integer Choose a random integer such that .
- Compute classically.
- If , you've already found a factor. Stop.
- Otherwise, continue.
-
Find order of modulo Find the smallest positive integer that satisfies .
-
Check if the order is even
- If is odd, go back to step 1 and pick a new .
- If is even, continue to step 4.
- Compute
- Check that and .
- If , go back to step 1 and pick a new .
- Otherwise, compute the gcds to extract the factors:
These will be nontrivial factors of .
- Recursively factor if needed
- If and/or are not prime, apply the algorithm recursively to factor them completely.
- Once all factors are prime, the factoring is complete.
Based on this procedure, it might not be obvious why a quantum computer is needed to complete this task. It's necessary because step 2, finding the order of modulo , is classically a very difficult problem. The complexity scales exponentially in the number . But with a quantum computer, we just have to make use of Quantum Phase Estimation to solve it. Step 4, finding the GCD of two integers, is actually a pretty easy thing to do classically. So, the only step that actually needs the power of a quantum computer is the order-finding step. We say that the factoring problem "reduces" to the order-finding problem.
The hard part: order finding
Now, we'll go through how we can use a quantum computer in order finding. First, let's clarify what we mean by "order." Of course, I already told you what the order means mathematically: it's the first non-zero integer such that But let's see if we can gain a little more intuition for this concept.
For small enough , we can just determine the order by calculating each power of , taking the modulus of that number, then stopping when we find the power that satisfies . That's what we did with our example, , above. Let's take a look at some graphs of these modular powers for some sample values of and :
Notice anything? These are periodic functions! And the order is the same as the period! So, order-finding is equivalent to period-finding.
Quantum computers are very well suited to finding the period of functions. For this, we can use an algorithmic subroutine called Quantum Phase Estimation. We discussed QPE and its relationship to the Quantum Fourier Transform in the previous module. For a detailed refresher, go to the QFT module or John Watrous' lesson on Quantum Phase Estimation in his Quantum Algorithms course. We'll go through the gist of the procedure now:
In Quantum Phase Estimation (QPE), we start with a unitary and an eigenstate of that unitary . Then, we use QPE to approximate the corresponding eigenvalue, which, since the operator is unitary, will be of the form . So, finding the eigenvalue is equivalent to finding the value of in the periodic function. The circuit looks like this:

where the number of control qubits (the top qubits in the figure above) determines the precision of the approximation.
In Shor’s algorithm, we use QPE on the unitary operator :
Here, denotes a computational basis state of the multi-qubit register, where the binary value of the qubits corresponds to the integer . For instance, if and , then is represented by the four-qubit basis state , since four qubits are required to encode numbers up to 15. (If this concept is unfamiliar, see the introductory Qiskit in classrooms module for a refresher on binary encoding of quantum states.)
Now, we need to figure out an eigenstate of this unitary. If we started in the state , we can see that each successive application of will multiply the state of our register by , and after applications we will arrive at the state again. For example with and :
So superpositions of the states in this cycle () of the form:
are all eigenstates of . (There are more eigenstates than just these. But we only care about the ones of the form above.)
Check your understanding
Read the question(s) below, think about your answer, then click the triangle to reveal the solution.
Find an eigenstate of the unitary corresponding to and .
Answer:
So, the order . The eigenstates we're interested in will be an equal superposition of all of the states that were cycled through above, with various phases:
Let's say we were able to initialize our qubit state into one of these eigenstates (spoiler — we're not. Or, at least not easily. We'll explain why and what we can do instead shortly). Then we could use QPE to estimate the corresponding eigenvalue, where . Then, we'll be able to determine the order by the simple equation:
But remember, I said that QPE estimates — it doesn't give us an exact value. We need the estimate to be good enough to differentiate between and . The more control qubits , we have, the better the estimate will be. In the problems at the end of the lesson, you'll be asked to determine the minimum needed to factor a number .
Now, we have to reconcile a problem. All of the above explanation of how to find begins with preparing the eigenstate . But we don't know how to do that without already knowing what is. The logic is circular. We need a way to estimate the eigenvalue without initializing the eigenstate.
Instead of starting with an eigenstate of , we can prepare the initial state into the -qubit state corresponding to in binary (as in, ). Although this state itself is obviously not an eigenstate of , it is a superposition over all of the eigenstates :
Check your understanding
Read the question(s) below, think about your answer, then click the triangle to reveal the solution.
Verify that is equivalent to the superposition over the eigenstates you found for and in the previous check-in question.
Answer:
The four eigenstates were: