Modular exponentiation is
exponentiation
In mathematics, exponentiation, denoted , is an operation (mathematics), operation involving two numbers: the ''base'', , and the ''exponent'' or ''power'', . When is a positive integer, exponentiation corresponds to repeated multiplication ...
performed over a
modulus. It is useful in
computer science
Computer science is the study of computation, information, and automation. Computer science spans Theoretical computer science, theoretical disciplines (such as algorithms, theory of computation, and information theory) to Applied science, ...
, especially in the field of
public-key cryptography
Public-key cryptography, or asymmetric cryptography, is the field of cryptographic systems that use pairs of related keys. Each key pair consists of a public key and a corresponding private key. Key pairs are generated with cryptographic alg ...
, where it is used in both
Diffie–Hellman key exchange and
RSA public/private keys.
Modular exponentiation is the remainder when an integer (the base) is raised to the power (the exponent), and divided by a
positive integer
In mathematics, the natural numbers are the numbers 0, 1, 2, 3, and so on, possibly excluding 0. Some start counting with 0, defining the natural numbers as the non-negative integers , while others start with 1, defining them as the positiv ...
(the modulus); that is, . From the definition of division, it follows that .
For example, given , and , dividing by leaves a remainder of .
Modular exponentiation can be performed with a ''negative'' exponent by finding the
modular multiplicative inverse
In mathematics, particularly in the area of arithmetic, a modular multiplicative inverse of an integer is an integer such that the product is congruent to 1 with respect to the modulus .. In the standard notation of modular arithmetic this cong ...
of modulo using the
extended Euclidean algorithm
In arithmetic and computer programming, the extended Euclidean algorithm is an extension to the Euclidean algorithm, and computes, in addition to the greatest common divisor (gcd) of integers ''a'' and ''b'', also the coefficients of Bézout's id ...
. That is:
:, where and .
Modular exponentiation is efficient to compute, even for very large integers. On the other hand, computing the modular
discrete logarithm
In mathematics, for given real numbers a and b, the logarithm \log_b(a) is a number x such that b^x=a. Analogously, in any group G, powers b^k can be defined for all integers k, and the discrete logarithm \log_b(a) is an integer k such that b^k=a ...
– that is, finding the exponent when given , , and – is believed to be difficult. This
one-way function
In computer science, a one-way function is a function that is easy to compute on every input, but hard to invert given the image of a random input. Here, "easy" and "hard" are to be understood in the sense of computational complexity theory, s ...
behavior makes modular exponentiation a candidate for use in cryptographic algorithms.
Direct method
The most direct method of calculating a modular exponent is to calculate directly, then to take this number modulo . Consider trying to compute , given , , and :
:
One could use a calculator to compute 4
13; this comes out to 67,108,864. Taking this value modulo 497, the answer is determined to be 445.
Note that is only one digit in length and that is only two digits in length, but the value is 8 digits in length.
In strong cryptography, is often at least 1024
bits. Consider and , both of which are perfectly reasonable values. In this example, is 77 digits in length and is 2 digits in length, but the value is 1,304 decimal digits in length. Such calculations are possible on modern computers, but the sheer magnitude of such numbers causes the speed of calculations to drop considerably. As and increase even further to provide better security, the value becomes unwieldy.
The time required to perform the exponentiation depends on the operating environment and the processor. The method described above requires multiplications to complete.
Memory-efficient method
Keeping the numbers smaller requires additional modular reduction operations, but the reduced size makes each operation faster, saving time (as well as memory) overall.
This algorithm makes use of the identity
:
The modified algorithm is:
:Inputs ''An integer (base), integer (exponent), and a positive integer (modulus)''
:Outputs ''The modular exponent where''
:# Initialise and loop variable
:# While do
:## Increment by 1
:## Calculate
:# Output
Note that at the end of every iteration through the loop, the equation holds true. The algorithm ends when the loop has been executed times. At that point contains the result of .
In summary, this algorithm increases by one until it is equal to . At every step multiplying the result from the previous iteration, , by and performing a modulo operation on the resulting product, thereby keeping the resulting a small integer.
The example , , and is presented again. The algorithm performs the iteration thirteen times:
:
:
:
:
:
:
:
:
:
:
:
:
:
The final answer for is therefore 445, as in the
direct method.
Like the first method, this requires multiplications to complete. However, since the numbers used in these calculations are much smaller than the numbers used in the first algorithm's calculations, the computation time decreases by a factor of at least in this method.
In pseudocode, this method can be performed the following way:
function modular_pow(base, exponent, modulus) is
if modulus = 1 then
return 0
c := 1
for e_prime = 0 to exponent-1 do
c := (c * base) mod modulus
return c
Right-to-left binary method
A third method drastically reduces the number of operations to perform modular exponentiation, while keeping the same
memory footprint
Memory footprint refers to the amount of main memory that a program uses or references while running.
The word footprint generally refers to the extent of physical dimensions that an object occupies, giving a sense of its size. In computing, t ...
as in the previous method. It is a combination of the previous method and a more general principle called
exponentiation by squaring (also known as ''binary exponentiation'').
First, it is required that the exponent be
converted to binary notation. That is, can be written as:
:
In such notation, the ''length'' of is bits. can take the value 0 or 1 for any such that . By definition, .
The value can then be written as:
:
The solution is therefore:
:
Pseudocode
The following is an example in pseudocode based on ''Applied Cryptography'' by
Bruce Schneier
Bruce Schneier (; born January 15, 1963) is an American cryptographer, computer security professional, privacy specialist, and writer. Schneier is an Adjunct Lecturer in Public Policy at the Harvard Kennedy School and a Fellow at the Berkman ...
.
[ Schneier 1996, p. 244.] The inputs
base,
exponent, and
modulus correspond to , , and in the equations given above.
function modular_pow(base, exponent, modulus) is
if modulus = 1 then
return 0
Assert :: (modulus - 1) * (modulus - 1) does not overflow base
result := 1
base := base mod modulus
while exponent > 0 do
if (exponent mod 2 1) then
result := (result * base) mod modulus
exponent := exponent >> 1
base := (base * base) mod modulus
return result
Note that upon entering the loop for the first time, the code variable
base is equivalent to . However, the repeated squaring in the third line of code ensures that at the completion of every loop, the variable
base is equivalent to , where is the number of times the loop has been iterated. (This makes the next working bit of the binary exponent
exponent, where the least-significant bit is
exponent0).
The first line of code simply carries out the multiplication in
. If is zero, no code executes since this effectively multiplies the running total by one. If instead is one, the variable
base (containing the value of the original base) is simply multiplied in.
In this example, the base is raised to the exponent .
The exponent is 1101 in binary. There are four binary digits, so the loop executes four times, with values , and .
First, initialize the result
to 1 and preserve the value of in the variable :
:
.
: Step 1) bit 1 is 1, so set
;
:: set
.
: Step 2) bit 2 is 0, so do not reset ;
:: set
.
: Step 3) bit 3 is 1, so set
;
:: set
.
: Step 4) bit 4 is 1, so set
;
:: This is the last step so we don't need to square .
We are done: is now
.
Here is the above calculation, where we compute to the power , performed modulo 497.
Initialize:
:
and
.
: Step 1) bit 1 is 1, so set
;
:: set
.
: Step 2) bit 2 is 0, so do not reset ;
:: set
.
: Step 3) bit 3 is 1, so set
;
:: set
.
: Step 4) bit 4 is 1, so set
;
We are done: is now
, the same result obtained in the previous algorithms.
The running time of this algorithm is
exponent. When working with large values of
exponent, this offers a substantial speed benefit over the previous two algorithms, whose time is
exponent. For example, if the exponent was 2
20 = 1048576, this algorithm would have 20 steps instead of 1048576 steps.
Implementation in Lua
function modPow(b, e, m)
if m 1 then
return 0
end
local r = 1
b = b % m
while e > 0 do
if e % 2 1 then
r = (r*b) % m
end
b = (b*b) % m
e = e >> 1 --use 'e = math.floor(e / 2)' on Lua 5.2 or older
end
return r
end
Left-to-right binary method
We can also use the bits of the exponent in left to right order. In practice, we would usually want the result modulo some modulus . In that case, we would reduce each multiplication result before proceeding. For simplicity, the modulus calculation is omitted here. This example shows how to compute
using left to right binary exponentiation. The exponent is 1101 in binary; there are 4 bits, so there are 4 iterations.
Initialize the result to 1:
.
: Step 1)
; bit 1 = 1, so compute
;
: Step 2)
; bit 2 = 1, so compute
;
: Step 3)
; bit 3 = 0, so we are done with this step;
: Step 4)
; bit 4 = 1, so compute
.
Minimum multiplications
In ''
The Art of Computer Programming, Vol. 2, Seminumerical Algorithms'', page 463,
Donald Knuth
Donald Ervin Knuth ( ; born January 10, 1938) is an American computer scientist and mathematician. He is a professor emeritus at Stanford University. He is the 1974 recipient of the ACM Turing Award, informally considered the Nobel Prize of comp ...
notes that contrary to some assertions, this method does always give the minimum possible number of multiplications. The smallest counterexample is for a power of 15, when the binary method needs six multiplications. Instead, form ''x''
3 in two multiplications, then ''x''
6 by squaring ''x''
3, then ''x''
12 by squaring ''x''
6, and finally ''x''
15 by multiplying ''x''
12 and ''x''
3, thereby achieving the desired result with only five multiplications. However, many pages follow describing how such sequences might be contrived in general.
Generalizations
Matrices
The -th term of any
constant-recursive sequence
In mathematics, an sequence, infinite sequence of numbers s_0, s_1, s_2, s_3, \ldots is called constant-recursive if it satisfies an equation of the form
:s_n = c_1 s_ + c_2 s_ + \dots + c_d s_,
for all n \ge d, where c_i are constant (mathemat ...
(such as
Fibonacci numbers
In mathematics, the Fibonacci sequence is a sequence in which each element is the sum of the two elements that precede it. Numbers that are part of the Fibonacci sequence are known as Fibonacci numbers, commonly denoted . Many writers begin the s ...
or
Perrin numbers) where each term is a linear function of previous terms can be computed efficiently modulo by computing , where is the corresponding
companion matrix. The above methods adapt easily to this application. This can be used for
primality testing of large numbers , for example.
; Pseudocode
A recursive algorithm for
ModExp(A, b, c)
= , where is a square matrix.
function Matrix_ModExp(Matrix A, int b, int c) is
if b 0 then
return I // The identity matrix
if (b mod 2 1) then
return (A * Matrix_ModExp(A, b - 1, c)) mod c
Matrix D := Matrix_ModExp(A, b / 2, c)
return (D * D) mod c
Finite cyclic groups
Diffie–Hellman key exchange uses exponentiation in finite cyclic groups. The above methods for modular matrix exponentiation clearly extend to this context. The modular matrix multiplication is simply replaced everywhere by the group multiplication .
Reversible and quantum modular exponentiation
In
quantum computing
A quantum computer is a computer that exploits quantum mechanical phenomena. On small scales, physical matter exhibits properties of wave-particle duality, both particles and waves, and quantum computing takes advantage of this behavior using s ...
, modular exponentiation appears as the bottleneck of
Shor's algorithm, where it must be computed by a circuit consisting of
reversible gates, which can be further broken down into
quantum gate
In quantum computing and specifically the quantum circuit model of computation, a quantum logic gate (or simply quantum gate) is a basic quantum circuit operating on a small number of qubits. Quantum logic gates are the building blocks of quantu ...
s appropriate for a specific physical device. Furthermore, in Shor's algorithm it is possible to know the base and the modulus of exponentiation at every call, which enables various circuit optimizations.
Software implementations
Because modular exponentiation is an important operation in computer science, and there are efficient algorithms (see above) that are much faster than simply exponentiating and then taking the remainder, many programming languages and arbitrary-precision integer libraries have a dedicated function to perform modular exponentiation:
*
Python's built-in
pow()
(exponentiation) functio
takes an optional third argument, the modulus
*
.NET Framework's
BigInteger
class has a
ModPow()
/code> method to perform modular exponentiation
* Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
's java.math.BigInteger
class has a method to perform modular exponentiation
* MATLAB
MATLAB (an abbreviation of "MATrix LABoratory") is a proprietary multi-paradigm programming language and numeric computing environment developed by MathWorks. MATLAB allows matrix manipulations, plotting of functions and data, implementat ...
's powermod
function from Symbolic Math Toolbox
*Wolfram Language has th
PowerMod
function
* Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed ...
's Math::BigInt
module has a bmodpow()
metho
to perform modular exponentiation
* Raku (programming language), Raku has a built-in routine expmod
.
* Go's big.Int
type contains an Exp()
(exponentiation) metho
whose third parameter, if non-nil, is the modulus
* PHP's BC Math library has a bcpowmod()
functio
to perform modular exponentiation
* The GNU Multiple Precision Arithmetic Library
GNU Multiple Precision Arithmetic Library (GMP) is a free software, free library for arbitrary-precision arithmetic, operating on Sign (mathematics), signed integers, Rational data type, rational numbers, and Floating-point arithmetic, floating-p ...
(GMP) library contains a mpz_powm()
functio
to perform modular exponentiation
* Custom Function @PowerMod()
/code> for FileMaker Pro (with 1024-bit RSA encryption example)
* Ruby
Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
's openssl
package has the OpenSSL::BN#mod_exp
metho
to perform modular exponentiation.
See also
* Montgomery reduction, for calculating the remainder when the modulus is very large.
* Kochanski multiplication, serializable method for calculating the remainder when the modulus is very large
* Barrett reduction, algorithm for calculating the remainder when the modulus is very large.
References
External links
*
* Paul Garrett
Fast Modular Exponentiation Java Applet
*
{{number theoretic algorithms
Cryptographic algorithms
Number theoretic algorithms
Modular arithmetic
Articles with example pseudocode