In
mathematics
Mathematics is a field of study that discovers and organizes methods, Mathematical theory, theories and theorems that are developed and Mathematical proof, proved for the needs of empirical sciences and mathematics itself. There are many ar ...
and
computer programming
Computer programming or coding is the composition of sequences of instructions, called computer program, programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of proc ...
, exponentiating by squaring is a general method for fast computation of large
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 ...
powers of a
number
A number is a mathematical object used to count, measure, and label. The most basic examples are the natural numbers 1, 2, 3, 4, and so forth. Numbers can be represented in language with number words. More universally, individual numbers can ...
, or more generally of an element of a
semigroup
In mathematics, a semigroup is an algebraic structure consisting of a set together with an associative internal binary operation on it.
The binary operation of a semigroup is most often denoted multiplicatively (just notation, not necessarily th ...
, like a
polynomial
In mathematics, a polynomial is a Expression (mathematics), mathematical expression consisting of indeterminate (variable), indeterminates (also called variable (mathematics), variables) and coefficients, that involves only the operations of addit ...
or a
square matrix
In mathematics, a square matrix is a Matrix (mathematics), matrix with the same number of rows and columns. An ''n''-by-''n'' matrix is known as a square matrix of order Any two square matrices of the same order can be added and multiplied.
Squ ...
. Some variants are commonly referred to as square-and-multiply algorithms or binary exponentiation. These can be of quite general use, for example in
modular arithmetic
In mathematics, modular arithmetic is a system of arithmetic operations for integers, other than the usual ones from elementary arithmetic, where numbers "wrap around" when reaching a certain value, called the modulus. The modern approach to mo ...
or powering of matrices. For semigroups for which
additive notation is commonly used, like
elliptic curve
In mathematics, an elliptic curve is a smooth, projective, algebraic curve of genus one, on which there is a specified point . An elliptic curve is defined over a field and describes points in , the Cartesian product of with itself. If the ...
s used in
cryptography
Cryptography, or cryptology (from "hidden, secret"; and ''graphein'', "to write", or ''-logy, -logia'', "study", respectively), is the practice and study of techniques for secure communication in the presence of Adversary (cryptography), ...
, this method is also referred to as double-and-add.
Basic method
Recursive version
The method is based on the observation that, for any integer
, one has:
If the exponent is zero then the answer is 1. If the exponent is negative then we can reuse the previous formula by rewriting the value using a positive exponent. That is,
Together, these may be implemented directly as the following
recursive algorithm
In computer science, recursion is a method of solving a computational problem where the solution depends on solutions to smaller instances of the same problem. Recursion solves such recursive problems by using functions that call themselves ...
:
Inputs: a real number ''x''; an integer ''n''
Output: x
n
function exp_by_squaring(x, n) is
if ''n'' < 0 then
return exp_by_squaring(1 / ''x'', −''n'')
else if ''n'' = 0 then
return 1
else if ''n'' is even then
return exp_by_squaring(''x'' × ''x'', ''n'' / 2)
else if ''n'' is odd then
return ''x'' × exp_by_squaring(''x'' × ''x'', (''n'' − 1) / 2)
end function
In each recursive call, the least significant digits of the
binary representation
A binary number is a number expressed in the base-2 numeral system or binary numeral system, a method for representing numbers that uses only two symbols for the natural numbers: typically "0" (zero) and "1" (one). A ''binary number'' may also ...
of is removed. It follows that the number of recursive calls is
the number of
bit
The bit is the most basic unit of information in computing and digital communication. The name is a portmanteau of binary digit. The bit represents a logical state with one of two possible values. These values are most commonly represented as ...
s of the binary representation of . So this algorithm computes this number of squares and a lower number of multiplication, which is equal to the number of in the binary representation of . This logarithmic number of operations is to be compared with the trivial algorithm which requires multiplications.
This algorithm is not
tail-recursive. This implies that it requires an amount of auxiliary memory that is roughly proportional to the number of recursive calls -- or perhaps higher if the amount of data per iteration is increasing.
The algorithms of the next section use a different approach, and the resulting algorithms needs the same number of operations, but use an auxiliary memory that is roughly the same as the memory required to store the result.
With constant auxiliary memory
The variants described in this section are based on the formula
:
If one applies recursively this formula, by starting with , one gets eventually an exponent equal to , and the desired result is then the left factor.
This may be implemented as a tail-recursive function:
Function exp_by_squaring(x, n)
return exp_by_squaring2(1, x, n)
Function exp_by_squaring2(y, x, n)
if n < 0 then return exp_by_squaring2(y, 1 / x, -n);
else if n = 0 then return y;
else if n is even then return exp_by_squaring2(y, x * x, n / 2);
else if n is odd then return exp_by_squaring2(x * y, x * x, (n - 1) / 2).
The iterative version of the algorithm also uses a bounded auxiliary space, and is given by
Function exp_by_squaring_iterative(x, n)
if n < 0 then
x := 1 / x;
n := -n;
if n = 0 then return 1
y := 1;
while n > 1 do
if n is odd then
y := x * y;
n := n - 1;
x := x * x;
n := n / 2;
return x * y
The correctness of the algorithm results from the fact that
is invariant during the computation; it is
at the beginning; and it is
at the end.
These algorithms use exactly the same number of operations as the algorithm of the preceding section, but the multiplications are done in a different order.
Computational complexity
A brief analysis shows that such an algorithm uses
squarings and at most
multiplications, where
denotes the
floor function
In mathematics, the floor function is the function that takes as input a real number , and gives as output the greatest integer less than or equal to , denoted or . Similarly, the ceiling function maps to the least integer greater than or eq ...
. More precisely, the number of multiplications is one less than the number of ones present in the
binary expansion
A binary number is a number expressed in the base-2 numeral system or binary numeral system, a method for representing numbers that uses only two symbols for the natural numbers: typically "0" ( zero) and "1" ( one). A ''binary number'' may als ...
of ''n''. For ''n'' greater than about 4 this is computationally more efficient than naively multiplying the base with itself repeatedly.
Each squaring results in approximately double the number of digits of the previous, and so, if multiplication of two ''d''-digit numbers is implemented in O(''d''
''k'') operations for some fixed ''k'', then the complexity of computing ''x''
''n'' is given by
:
2''k''-ary method
This algorithm calculates the value of ''x
n'' after expanding the exponent in base 2
''k''. It was first proposed by
Brauer Brauer or Bräuer is a surname of German origin, meaning "brewer". Notable people with the name include:-
* Alfred Brauer (1894–1985), German-American mathematician, brother of Richard
* Andreas Brauer (born 1973), German film producer
* Arik Bra ...
in 1939. In the algorithm below we make use of the following function ''f''(0) = (''k'', 0) and ''f''(''m'') = (''s'', ''u''), where ''m'' = ''u''·2
''s'' with ''u'' odd.
Algorithm:
;Input: An element ''x'' of ''G'', a parameter ''k'' > 0, a non-negative integer and the precomputed values
.
;Output: The element ''x
n'' in ''G''
y := 1; i := l - 1
while i ≥ 0 do
(s, u) := f(n
i)
for j := 1 to k - s do
y := y
2
y := y * x
u
for j := 1 to s do
y := y
2
i := i - 1
return y
For optimal efficiency, ''k'' should be the smallest integer satisfying
:
Sliding-window method
This method is an efficient variant of the 2
''k''-ary method. For example, to calculate the exponent 398, which has binary expansion (110 001 110)
2, we take a window of length 3 using the 2
''k''-ary method algorithm and calculate 1, x
3, x
6, x
12, x
24, x
48, x
49, x
98, x
99, x
198, x
199, x
398.
But, we can also compute 1, x
3, x
6, x
12, x
24, x
48, x
96, x
192, x
199, x
398, which saves one multiplication and amounts to evaluating (110 001 110)
2
Here is the general algorithm:
Algorithm:
;Input: An element ''x'' of ''G'', a non negative integer , a parameter ''k'' > 0 and the pre-computed values
.
;Output: The element ''x
n'' ∈ ''G''.
Algorithm:
y := 1; i := l - 1
while i > -1 do
if n
i = 0 then
y := y
2
i := i - 1
else
s := max
while n
s = 0 do
s := s + 1
[In this line, the loop finds the longest string of length less than or equal to ''k'' ending in a non-zero value. Not all odd powers of 2 up to need be computed, and only those specifically involved in the computation need be considered.]
for h := 1 to i - s + 1 do
y := y
2
u := (n
i, n
i-1, ..., n
s)
2
y := y * x
u
i := s - 1
return y
Montgomery's ladder technique
Many algorithms for exponentiation do not provide defence against
side-channel attack
In computer security, a side-channel attack is a type of security exploit that leverages information inadvertently leaked by a system—such as timing, power consumption, or electromagnetic or acoustic emissions—to gain unauthorized access to ...
s. Namely, an attacker observing the sequence of squarings and multiplications can (partially) recover the exponent involved in the computation. This is a problem if the exponent should remain secret, as with many
public-key cryptosystems. A technique called "
Montgomery's ladder"
addresses this concern.
Given the
binary expansion
A binary number is a number expressed in the base-2 numeral system or binary numeral system, a method for representing numbers that uses only two symbols for the natural numbers: typically "0" ( zero) and "1" ( one). A ''binary number'' may als ...
of a positive, non-zero integer ''n'' = (''n''
''k''−1...''n''
0)
2 with ''n''
k−1 = 1, we can compute ''x
n'' as follows:
x
1 = x; x
2 = x
2
for i = k - 2 to 0 do
if n
i = 0 then
x
2 = x
1 * x
2; x
1 = x
12
else
x
1 = x
1 * x
2; x
2 = x
22
return x
1
The algorithm performs a fixed sequence of operations (
up to Two Mathematical object, mathematical objects and are called "equal up to an equivalence relation "
* if and are related by , that is,
* if holds, that is,
* if the equivalence classes of and with respect to are equal.
This figure of speech ...
log ''n''): a multiplication and squaring takes place for each bit in the exponent, regardless of the bit's specific value. A similar algorithm for multiplication by doubling exists.
This specific implementation of Montgomery's ladder is not yet protected against cache
timing attack
In cryptography, a timing attack is a side-channel attack in which the attacker attempts to compromise a cryptosystem by analyzing the time taken to execute cryptographic algorithms. Every logical operation in a computer takes time to execute, an ...
s: memory access latencies might still be observable to an attacker, as different variables are accessed depending on the value of bits of the secret exponent. Modern cryptographic implementations use a "scatter" technique to make sure the processor always misses the faster cache.
Fixed-base exponent
There are several methods which can be employed to calculate ''x
n'' when the base is fixed and the exponent varies. As one can see,
precomputation
In algorithms, precomputation is the act of performing an initial computation before Run time (program lifecycle phase), run time to generate a lookup table that can be used by an algorithm to avoid repeated computation each time it is executed. ...
s play a key role in these algorithms.
Yao's method
Yao's method is orthogonal to the -ary method where the exponent is expanded in radix and the computation is as performed in the algorithm above. Let , , , and be integers.
Let the exponent be written as
:
where
for all