Modular exponentiation Created 2026-10-06 Updated 2026-10-20
Modular exponentiation computes the remainder for an integer base , a nonnegative integer exponent , and, here, an integer modulus . It applies exponentiation by squaring while reducing after each multiplication, including each squaring. The result is the unique representative in . There is no requirement that the base be coprime to the modulus when the exponent is nonnegative.[ref]
Take , , and . Initialize ; the remaining digits give
Hence . The final operation multiplies by , since the preceding square has already been reduced. The computation never needs to construct .
In general reduce the base first, . For , initialize and process the remaining binary digits with , followed, for a digit one, by . The loop invariant is
where is the processed prefix value. The congruence is preserved because modular arithmetic respects multiplication: if , then and . Thus changing representatives never changes the final congruence class.
Both factors in every product are less than , so the unreduced product is less than , and the stored result is again less than . The same bounds hold for a gigantic exponent, such as : there are squarings, each on bounded-size residues. For base two, the corresponding ordinary power would have binary digits. The benefit is avoiding the huge ordinary power altogether, rather than constructing it and taking one final remainder. Initial reduction is essential when the supplied base is much larger than the modulus.
For , return under the same empty-product convention as exponentiation by squaring. For , require , find the modular multiplicative inverse , and compute ; the extended Euclidean algorithm can find that inverse. Its cost is separate from the positive-exponent binary powering multiplication count. For example, , while is undefined because and are not coprime.
For and order , multiplication by modulo is a unitary operator. On the orbit of one it cyclically permutes basis states. The displayed orthonormal eigenstates have eigenvalues , and . Thus quantum phase estimation on this efficiently prepared state samples a uniform without knowing . Controlled powers are implemented by quantum modular exponentiation. Sufficient phase resolution allows continued-fraction recovery in quantum order finding; the reduced denominator equals only when is coprime to .
Let be a unitary operator and suppose initially that the target is an eigenstate with , . Use control qubits, so . Hadamard gates prepare the uniform superposition . For each binary control position , apply the controlled unitary gate . The resulting state is
Apply the inverse quantum Fourier transform, with convention , and measure the control. The exact amplitude and probability are
For an exactly representable phase , orthogonality of roots of unity makes the outcome certain. Otherwise the finite geometric series gives
The estimate is , with phases interpreted modulo one.
To prove an error bound, choose a nearest label to on the circular grid and put in the interval . For , concavity of sine on gives , while . Therefore the nearest-integer success bound for quantum phase estimation is
Here . At an exact grid point the probability is one. If two nearest labels tie, either one separately has the displayed lower bound.
For high confidence one can prove a stronger quantum phase estimation tail bound. Let be the centered distance between and , chosen with . The denominator estimate implies away from the exact-phase case. A label at circular integer distance from has , and there are at most two labels at each such distance. For , summing the tails gives
On the complementary event the circular phase error is at most . Thus, for desired bits of accuracy, take with and to obtain
Taking makes the right side at most . This adds only control qubits. Efficient QFT is not by itself a guarantee of efficient controlled powers of an arbitrary : implementing them by repeated oracle calls uses calls. The modular-arithmetic application has efficient powers, as follows.
Assume and , and let be the multiplicative order of modulo . Define the unitary operator on , and extend it as the identity on unused computational-basis labels of the binary register. Coprimality makes multiplication a permutation, so this extension really is unitary. The orbit of consists of the distinct states . Its modular multiplication eigenstates are
The last relation follows by shifting the index cyclically; orthogonality follows from the finite Fourier sum. We do not need to know to prepare one of these eigenstates: the readily prepared target obeys
Running quantum phase estimation on this state produces the mixture of the eigenphase distributions, each with weight , because the target eigenstates are orthogonal. Thus it samples a uniformly random phase label and estimates with the bounds just proved. Equivalently the state before the inverse QFT is , which is obtained by quantum modular exponentiation directly.
The controlled power multiplies by , whose constant is computed by repeated squaring. Under the assumed efficient modular exponentiation, these controlled multiplications and the QFT use a number of gates polynomial in the register lengths. Taking requires only phase qubits. The nearest-label event has probability at least and yields an estimate within of . Since , continued-fraction recovery in quantum order finding then identifies the reduced fraction . The denominator is , not necessarily : when and are coprime it is the desired order, and when they are not it is only a divisor. One may test candidate denominators using modular exponentiation and repeat with fresh samples; denominators from successful samples can also be combined by a least common multiple. The probability of a nearest-label sample with coprime to is at least . These qualifications explain exactly what the phase estimate yields without falsely assuming that the unknown order or an eigenstate was available at the start.
Let . In the Shor algorithm, first use classical arithmetic to deal with even and perfect powers, and to reject prime inputs. Perfect-power recognition and primality testing have polynomial-time classical algorithms. Factoring a perfect power , with , already gives a nontrivial factor . We may therefore consider an odd composite with at least two distinct prime factors.
Choose uniformly from and compute its greatest common divisor with using the Euclidean algorithm. A proper nontrivial divisor ends the computation. Otherwise is a unit, and the remaining task is quantum order finding. Set
Prepare a uniform quantum superposition in a -qubit register and use quantum modular exponentiation in a second register to obtain
Repeated squaring and reversible modular multiplication implement this step with polynomially many quantum gates in . Apply the inverse quantum Fourier transform to the first register and perform a quantum measurement in the computational basis, obtaining . Measuring the second register first, and Fourier-transforming the resulting periodic coset, gives the same distribution of .
Here is a quantitative quantum Fourier sampling bound for order finding. If , multiplication by cycles its orbit states. The Fourier eigenstates of that cycle have eigenvalues , and the initial state has squared overlap with each, for . Therefore
Conditioned on a particular eigenphase , its nearest integer outcome obeys and has probability at least . Indeed the absolute amplitude is , where . For , the numerator is at least and the denominator at most ; the limiting value at is one.
If , the fraction is reduced, and gives
Use continued-fraction recovery in quantum order finding. The relevant approximation theorem says that reduced fractions satisfying are continued fraction convergents of . For an input rational of digits, their candidates can be enumerated classically in time, and their denominators are at most the reduced input denominator. This is the supplied continued-fraction result; discard candidate denominators exceeding . A zero measurement is treated as a failed order-finding sample.
For each remaining even candidate denominator , compute by repeated squaring, and try and . Return only a divisor with ; otherwise repeat the quantum sample or choose another . This candidate-denominator gcd post-processing cannot return an incorrect factor, since its output is checked directly. When the recovered denominator is the true even multiplicative order and the square root of one is nontrivial, part (i) guarantees success. Checking before trying the gcds is also a valid, more restrictive convention; the single-run distinction matters in part (iii).
Two further standard quantitative facts explain why repetitions remain efficient. First, for a uniformly chosen unit modulo an odd integer with at least two distinct prime divisors, the probability of a useful unit in Shor factorization is at least : its true multiplicative order is even and . To see the source of this bound, the Chinese remainder theorem for unit groups makes the prime-power components independent. Each odd-prime-power unit group is cyclic. If its 2-primary order is , the probability of the largest possible value of is , and the probability of any specified smaller value is at most . Failure requires all components to have the same : either all zero, making odd, or all the same positive value, making the halfway power in every component. Conditioning on one component, the chance another component matches it is at most , so total failure is at most .
Second, the fraction of phase numerators coprime to is , where is the Euler totient function. The elementary totient-ratio lower bound suffices: if the distinct prime divisors are , then and . The totient product formula therefore gives
Thus for a good , the probability of sampling a coprime phase numerator with the required accuracy is at least . This is inverse-polynomial in the input length, so polynomially many repetitions achieve any fixed success probability. The quantum Fourier transform uses elementary rotations and Hadamard gates in the ideal gate description, and the other quantum and classical stages are polynomial in .
The reduction is therefore polynomial in the bit length:
A small denominator need not itself be the true multiplicative order; verification of the final factor is essential, and no guarantee is claimed for every individual sample.
Choose a power of two with
Since the multiplicative order is less than , this guarantees . Prepare two quantum registers in the state
and use quantum modular exponentiation to obtain
Measure the second register. The order as the exact period of modular exponentiation implies that, conditional on the measured value, the first register is a normalized truncated periodic coset
where is the largest integer for which .
Apply the quantum Fourier transform to the first register and measure it, obtaining . The supplied Fourier-transform theorem states that, with probability of order , is an integer nearest to for some coprime to . On that event,
The supplied continued-fraction theorem, applied through continued-fraction recovery in quantum order finding, therefore recovers the reduced fraction from . Because and are coprime, its denominator is the exact order . The candidate is checked classically by verifying .
The quantum Fourier transform, quantum modular exponentiation, continued-fraction algorithm, and final modular check all take polynomial time in . Since , the successful event has probability of order , as required.
The input size of an integer factorization problem is its number of bits . Trial division up to is exponential in ; advanced classical algorithms do substantially better, but no general polynomial-time classical factoring algorithm is known. The heuristic general-purpose general number field sieve has subexponential rather than polynomial scaling, roughly . This describes known algorithmic performance, not a proof that efficient classical factoring is impossible or that every large integer is difficult.
Choose with . A nontrivial greatest common divisor already supplies a factor; otherwise find the multiplicative order of modulo . If is even and , then
Minimality of the order also excludes , so factor extraction from an even modular order gives nontrivial factors through . Unhelpful choices of or odd orders require another trial. For , has successive residues and order four, giving
Computing the powers is easy by repeated squaring; discovering a large order is the step accelerated by Shor's algorithm.[ref]
Put and suppose . For each residue class , let
These are normalized uniform superpositions of the arguments with the same modular-exponentiation value. Their amplitudes repeat at separation within the finite register window. Exact cyclic periodicity requires . The correctly normalized entangled register state is
The equal prefactor in the displayed algorithm is exact when , for then every . It is not generally exact for an arbitrary unknown order. A physical implementation uses quantum modular exponentiation as a reversible map; its specified action on second-register input zero is extended to a unitary operator on the whole register space.
For the illustrative , and , the four first-register states are
Applying the positive-sign quantum Fourier transform to the general state gives
The bracket is a finite geometric Fourier amplitude. If , it vanishes unless for , when it equals . Hence
The second-register states are orthogonal, so their different phases do not change the marginal first-register probabilities. Measurement gives
In the example the possible outcomes are . A nonzero observed ratio estimates , not a prime factor directly. Reducing it gives denominator ; repeating avoids uninformative outcomes or recovers missing order factors. For example, or gives denominator four, whereas alone gives only two.
When , the Fourier probabilities have narrow peaks near instead of support only on an exact reciprocal grid. The general marginal distribution is
Choosing supplies the usual precision for continued-fraction recovery in quantum order finding: a nearest grid sample differs from the target rational by at most . Candidate denominators and extracted divisors are checked classically, and repetitions provide useful samples. The small example works exactly because its order divides the register size; it is not a general precision guarantee for factoring every four-bit integer.
Figure 1.
Exact reciprocal-period sampling for order four and broadened peaks when the order does not divide the register
. Details.
A sufficiently large reliable quantum computer would undermine RSA by efficient factorization. The related discrete-logarithm algorithm also threatens Diffie-Hellman key exchange and elliptic-curve public-key schemes. This does not imply that every communication scheme or symmetric cipher is broken by the same algorithm; post-quantum cryptography studies alternatives based on other problems. The mathematical speedup assumes a scalable quantum computation with enough precision and error control, not merely a small demonstration of factoring fifteen.