Shor's algorithm is a quantum algorithm for finding the prime factors of an integer. It was developed in 1994 by the American mathematician Peter Shor. It is one of the few known quantum algorithms with compelling potential applications and strong evidence of superpolynomial speedup compared to best known classical (that is, non-quantum) algorithms. On the other hand, factoring numbers of practical significance requires far more qubits than available in the near future. Another concern is that noise in quantum circuits may undermine results, requiring additional qubits for quantum error correction.

Shor proposed multiple similar algorithms solving the factoring problem, the discrete logarithm problem, and the period finding problem. "Shor's algorithm" usually refers to his algorithm solving factoring, but may also refer to each of the three. The discrete logarithm algorithm and the factoring algorithm are instances of the period finding algorithm, and all three are instances of the hidden subgroup problem.

Shor's algorithm allows to factor an integer  on a quantum computer in polylogarithmic time, meaning that the running time of the algorithm is polynomial in . Specifically, it takes quantum gates of order  using fast multiplication, or even  utilizing the asymptotically fastest multiplication algorithm currently known due to Harvey and Van Der Hoeven, thus demonstrating that the integer factorization problem can be efficiently solved on a quantum computer and is consequently in the complexity class BQP. This is significantly faster than the most efficient known classical factoring algorithm, the general number field sieve, which works in sub-exponential time: .

Feasability and impact 

If a quantum computer with a sufficient number of qubits could operate without succumbing to quantum noise and other quantum-decoherence phenomena, then Shor's algorithm could be used to break public-key cryptography schemes, such as

 The RSA scheme
 The Finite Field Diffie-Hellman key exchange
 The Elliptic Curve Diffie-Hellman key exchange

RSA is based on the assumption that factoring large integers is computationally intractable. As far as is known, this assumption is valid for classical (non-quantum) computers; no classical algorithm is known that can factor integers in polynomial time. However, Shor's algorithm shows that factoring integers is efficient on an ideal quantum computer, so it may be feasible to defeat RSA by constructing a large quantum computer. It was also a powerful motivator for the design and construction of quantum computers, and for the study of new quantum-computer algorithms. It has also facilitated research on new cryptosystems that are secure from quantum computers, collectively called post-quantum cryptography.

Physical implementation 
Given the high error rates of contemporary quantum computers and too few qubits to use quantum error correction, laboratory demonstrations obtain correct results only in a fraction of attempts.

In 2001, Shor's algorithm was demonstrated by a group at IBM, who factored  into , using an NMR implementation of a quantum computer with  qubits. After IBM's implementation, two independent groups implemented Shor's algorithm using photonic qubits, emphasizing that multi-qubit entanglement was observed when running the Shor's algorithm circuits. In 2012, the factorization of  was performed with solid-state qubits. Later, in 2012, the factorization of  was achieved. In 2019, an attempt was made to factor the number  using Shor's algorithm on an IBM Q System One, but the algorithm failed because of accumulating errors.  Though larger numbers have been factored by quantum computers using other algorithms, these algorithms are similar to classical brute-force checking of factors, so unlike Shor's algorithm, they are not expected to ever perform better than classical factoring algorithms.

Theoretical analyses of Shor's algorithm assume a quantum computer free of noise and errors. However, near-term practical implementations will have to deal with such undesired phenomena (when more qubits are available, Quantum error correction can help). In 2023, Jin-Yi Cai studied the impact of noise and concluded that "Shor's Algorithm Does Not Factor Large Integers in the Presence of Noise."

Algorithm 
The problem that we are trying to solve is: given an odd composite number , find its integer factors.

To achieve this, Shor's algorithm consists of two parts:

 A classical reduction of the factoring problem to the problem of order-finding. This reduction is similar to that used for other factoring algorithms, such as the quadratic sieve.
 A quantum algorithm to solve the order-finding problem.

Classical reduction 
A complete factoring algorithm is possible using extra classical methods if we're able to factor  into just two integers  and ; therefore the algorithm only needs to achieve that.

A basic observation is that, using Euclid's algorithm, we can always compute the GCD between two integers efficiently. In particular, this means we can check efficiently whether  is even, in which case 2 is trivially a factor. Let us thus assume that  is odd for the remainder of this discussion. Afterwards, we can use efficient classical algorithms to check if  is a prime power; again, the rest of the algorithm requires that  is not a prime power, and if it is,  has been completely factored.

If those easy cases do not produce a nontrivial factor of , the algorithm proceeds to handle the remaining case. We pick a random integer . A possible nontrivial divisor of  can be found by computing , which can be done classically and efficiently using the Euclidean algorithm. If this produces a nontrivial factor (meaning ), the algorithm is finished, and the other nontrivial factor is . If a nontrivial factor was not identified, then that means that  and the choice of  are coprime. Here, the algorithm runs the quantum subroutine, which will return the order  of , meaning

The quantum subroutine requires that  and  are coprime, which is true since at this point in the algorithm,  did not produce a nontrivial factor of . It can be seen from the equivalence that  divides , written . This can be factored using difference of squares:Since we have factored the expression in this way, the algorithm doesn't work for odd  (because  must be an integer), meaning the algorithm would have to restart with a new . Hereafter we can therefore assume  is even. It cannot be the case that , since this would imply , which would contradictorily imply that  would be the order of , which was already . At this point, it may or may not be the case that . If it is not true that , then that means we are able to find a nontrivial factor of . We computeIf , then that means  was true, and a nontrivial factor of  cannot be achieved from , and the algorithm must restart with a new . Otherwise, we have found a nontrivial factor of , with the other being , and the algorithm is finished. For this step, it is also equivalent to compute ; it will produce a nontrivial factor if  is nontrivial, and will not if it's trivial (where ).

The algorithm restated shortly follows: let  be odd, and not a prime power. We want to output two nontrivial factors of .It has been shown that this will be likely to succeed after a few runs. In practice, a single call to the quantum order-finding subroutine is enough to completely factor  with very high probability of success if one uses a more advanced reduction.

Quantum order-finding subroutine 
The goal of the quantum subroutine of Shor's algorithm is, given coprime integers  and , to find the order  of  modulo , which is the smallest positive integer such that . To achieve this, Shor's algorithm uses a quantum circuit involving two registers. The second register uses  qubits, where  is the smallest integer such that . The size of the first register determines how accurate of an approximation the circuit produces. It can be shown that using  qubits gives sufficient accuracy to find . The exact quantum circuit depends on the parameters  and , which define the problem.

The algorithm consists of two main steps:

 Use quantum phase estimation with unitary  representing the operation of multiplying by  (modulo ), and input state  (where the second register is  made from  qubits). The eigenvalues of this  encode information about the period, and  can be seen to be writable as a sum of its eigenvectors. Thanks to these properties, the quantum phase estimation stage gives as output a random integer of the form  for random .
 Use the continued fractions algorithm to extract the period  from the measurement outcomes obtained in the previous stage. This is a procedure to post-process (with a classical computer) the measurement data obtained from measuring the output quantum states, and retrieve the period.

The connection with quantum phase estimation was not discussed in the original formulation of Shor's algorithm, but was later proposed by Kitaev.

Quantum phase estimation 

In general the quantum phase estimation algorithm, for any unitary  and eigenstate  such that , sends inputs states  into output states close to , where  is an integer close to . In other words, it sends each eigenstate  of  into a state close to the associated eigenvalue. For the purposes of quantum order-finding, we employ this strategy using the unitary defined by the actionThe action of  on states  with  is not crucial to the functioning of the algorithm, but needs to be included to ensure the overall transformation is a well-defined quantum gate. Implementing the circuit for quantum phase estimation with  requires being able to efficiently implement the gates . This can be accomplished via modular exponentiation, which is the slowest part of the algorithm.
The gate thus defined satisfies , which immediately implies that its eigenvalues are the -th roots of unity . Furthermore, each eigenvalue  has an eigenvector of the form , and these eigenvectors are such that

where the last identity follows from the geometric series formula, which implies .

Using quantum phase estimation on an input state  would result in an output  with each  representing a superposition of integers that approximate , with the most accurate measurement having a chance of  of being measured (which can be made arbitrarily high using extra qubits). Thus using as input  instead, the output is a superposition of such states with . In other words, using this input amounts to running quantum phase estimation on a superposition of eigenvectors of . More explicitly, the quantum phase estimation circuit implements the transformationMeasuring the first register, we now have a balanced probability  to find each , each one giving an integer approximation to , which can be divided by  to get a decimal approximation for .

Continued fraction algorithm to retrieve the period 
Then, we apply the continued fractions algorithm to find integers  and , where  gives the best fraction approximation for the approximation measured from the circuit, for  and coprime  and . The number of qubits in the first register, , which determines the accuracy of the approximation, guarantees thatgiven the best approximation from the superposition of  was measured (which can be made arbitrarily likely by using extra bits and truncating the output). However, while  and  are coprime, it may be the case that  and  are not coprime. Because of that,  and  may have lost some factors that were in  and . This can be remedied by rerunning the quantum subroutine an arbitrary number of times, to produce a list of fraction approximationswhere  is the number of times the algorithm was run. Each  will have different factors taken out of it because the circuit will (likely) have measured multiple different possible values of . To recover the actual  value, we can take the least common multiple of each :The least common multiple will be the order  of the original integer  with high probability.

Choosing the size of the first register 
Phase estimation requires choosing the size of the first register to determine the accuracy of the algorithm, and for the quantum subroutine of Shor's algorithm,  qubits is sufficient to guarantee that the optimal bitstring measured from phase estimation (meaning the  where  is the most accurate approximation of the phase from phase estimation) will allow the actual value of  to be recovered.

Each  before measurement in Shor's algorithm represents a superposition of integers approximating . Let  represent the most optimal integer in . The following theorem guarantees that the continued fractions algorithm will recover  from :

 As  is the optimal bitstring from phase estimation,  is accurate to  by  bits. Thus,which implys that the continued fractions algorithm will recover  and  (or with their greatest common divisor taken out).

The bottleneck 
The runtime bottleneck of Shor's algorithm is quantum modular exponentiation, which is by far slower than the quantum Fourier transform and classical pre-/post-processing. There are several approaches to constructing and optimizing circuits for modular exponentiation. The simplest and (currently) most practical approach is to mimic conventional arithmetic circuits with reversible gates, starting with ripple-carry adders. Knowing the base and the modulus of exponentiation facilitates further optimizations. Reversible circuits typically use on the order of  gates for  qubits. Alternative techniques asymptotically improve gate counts by using quantum Fourier transforms, but are not competitive with fewer than 600 qubits owing to high constants.

Period finding and discrete logarithms 
Shor's algorithms for the discrete log and the order finding problems are instances of an algorithm solving the period finding problem.. All three are instances of the hidden subgroup problem.

Shor's algorithm for discrete logarithms 
Given a group  with order  and generator , suppose we know that , for some , and we wish to compute , which is the discrete logarithm: . Consider the abelian group , where each factor corresponds to modular addition of values. Now, consider the function

This gives us an abelian hidden subgroup problem, where  corresponds to a group homomorphism. The kernel corresponds to the multiples of . So, if we can find the kernel, we can find . A quantum algorithm for solving this problem exists. This algorithm is, like the factor-finding algorithm, due to Peter Shor and both are implemented by creating a superposition through using Hadamard gates, followed by implementing  as a quantum transform, followed finally by a quantum Fourier transform. Due to this, the quantum algorithm for computing the discrete logarithm is also occasionally referred to as "Shor's Algorithm."

The order-finding problem can also be viewed as a hidden subgroup problem. To see this, consider the group of integers under addition, and for a given  such that: , the function

For any finite abelian group , a quantum algorithm exists for solving the hidden subgroup for  in polynomial time.

See also 
 GEECM, a factorization algorithm said to be "often much faster than Shor's"
 Grover's algorithm

References

Further reading 
 .
 Phillip Kaye, Raymond Laflamme, Michele Mosca, An introduction to quantum computing, Oxford University Press, 2007, 
 "Explanation for the man in the street" by Scott Aaronson, "approved" by Peter Shor. (Shor wrote "Great article, Scott! That’s the best job of explaining quantum computing to the man on the street that I’ve seen."). An alternate metaphor for the QFT was presented in one of the comments. Scott Aaronson suggests the following 12 references as further reading (out of "the 10105000 quantum algorithm tutorials that are already on the web."):
 . Revised version of the original paper by Peter Shor ("28 pages, LaTeX. This is an expanded version of a paper that appeared in the Proceedings of the 35th Annual Symposium on Foundations of Computer Science, Santa Fe, NM, Nov. 20--22, 1994. Minor revisions made January, 1996").
 Quantum Computing and Shor's Algorithm, Matthew Hayward's Quantum Algorithms Page, 2005-02-17, imsa.edu, LaTeX2HTML version of the original LaTeX document, also available as PDF or postscript document.
 Quantum Computation and Shor's Factoring Algorithm, Ronald de Wolf, CWI and University of Amsterdam, January 12, 1999, 9 page postscript document.
 Shor's Factoring Algorithm, Notes from Lecture 9 of Berkeley CS 294–2, dated 4 Oct 2004, 7 page postscript document.
 Chapter 6 Quantum Computation, 91 page postscript document, Caltech, Preskill, PH229.
 Quantum computation: a tutorial by Samuel L. Braunstein.
 The Quantum States of Shor's Algorithm, by Neal Young, Last modified: Tue May 21 11:47:38 1996.
 III. Breaking RSA Encryption with a Quantum Computer: Shor's Factoring Algorithm, Lecture notes on Quantum computation, Cornell University, Physics 481–681, CS 483; Spring, 2006 by N. David Mermin. Last revised 2006-03-28, 30 page PDF document.
 
   This paper is a written version of a one-hour lecture given on Peter Shor's quantum factoring algorithm. 22 pages.
 Chapter 20 Quantum Computation, from Computational Complexity: A Modern Approach, Draft of a book: Dated January 2007, Sanjeev Arora and Boaz Barak, Princeton University. Published as Chapter 10 Quantum Computation of Sanjeev Arora, Boaz Barak, "Computational Complexity: A Modern Approach", Cambridge University Press, 2009, 
 A Step Toward Quantum Computing: Entangling 10 Billion Particles, from "Discover Magazine", Dated January 19, 2011.
 Josef Gruska - Quantum Computing Challenges also in Mathematics unlimited: 2001 and beyond, Editors Björn Engquist, Wilfried Schmid, Springer, 2001,

External links
 Version 1.0.0 of libquantum: contains a C language implementation of Shor's algorithm with their simulated quantum computer library, but the width variable in shor.c should be set to 1 to improve the runtime complexity.
 PBS Infinite Series created two videos explaining the math behind Shor's algorithm, "How to Break Cryptography" and "Hacking at Quantum Speed with Shor's Algorithm".

Quantum algorithms
Integer factorization algorithms
Post-quantum cryptography