Misplaced Pages

Exponentiation by squaring

Article snapshot taken from Wikipedia with creative commons attribution-sharealike license. Give it a read and then ask your questions in the chat. We can research this topic together.
(Redirected from Square-and-multiply algorithm) Algorithm for fast exponentiation
This article may be confusing or unclear to readers. Please help clarify the article. There is a discussion about this on talk:Exponentiation by squaring § Least significant bit is first. (May 2022) (Learn how and when to remove this message)
This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.
Find sources: "Exponentiation by squaring" – news · newspapers · books · scholar · JSTOR (February 2018) (Learn how and when to remove this message)

In mathematics and computer programming, exponentiating by squaring is a general method for fast computation of large positive integer powers of a number, or more generally of an element of a semigroup, like a polynomial or a square matrix. 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 or powering of matrices. For semigroups for which additive notation is commonly used, like elliptic curves used in 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 n > 0 {\displaystyle n>0} , one has: x n = { x ( x 2 ) ( n 1 ) / 2 , if  n  is odd ( x 2 ) n / 2 , if  n  is even {\displaystyle x^{n}={\begin{cases}x\,(x^{2})^{(n-1)/2},&{\mbox{if }}n{\mbox{ is odd}}\\(x^{2})^{n/2},&{\mbox{if }}n{\mbox{ is even}}\end{cases}}}

If the exponent n 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, x n = ( 1 x ) n . {\displaystyle x^{n}=\left({\frac {1}{x}}\right)^{-n}\,.}

Together, these may be implemented directly as the following recursive algorithm:

 In: a real number x; an integer n
 Out: x
 exp_by_squaring(x, n)
   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 of n is removed. It follows that the number of recursive calls is log 2 n , {\displaystyle \lceil \log _{2}n\rceil ,} the number of bits of the binary representation of n. So this algorithm computes this number of squares and a lower number of multiplication, which is equal to the number of 1 in the binary representation of n. This logarithmic number of operations is to be compared with the trivial algorithm which requires n − 1 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

y x n = { ( y x ) ( x 2 ) ( n 1 ) / 2 , if  n  is odd y ( x 2 ) n / 2 , if  n  is even . {\displaystyle yx^{n}={\begin{cases}(yx)\,(x^{2})^{(n-1)/2},&{\mbox{if }}n{\mbox{ is odd}}\\y\,(x^{2})^{n/2},&{\mbox{if }}n{\mbox{ is even}}.\end{cases}}}

If one applies recursively this formula, by starting with y = 1, one gets eventually an exponent equal to 0, 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 y x n {\displaystyle yx^{n}} is invariant during the computation; it is 1 x n = x n {\displaystyle 1\cdot x^{n}=x^{n}} at the beginning; and it is y x 1 = x y {\displaystyle yx^{1}=xy} 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 log 2 n {\displaystyle \lfloor \log _{2}n\rfloor } squarings and at most log 2 n {\displaystyle \lfloor \log _{2}n\rfloor } multiplications, where {\displaystyle \lfloor \;\rfloor } denotes the floor function. More precisely, the number of multiplications is one less than the number of ones present in the binary expansion 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) operations for some fixed k, then the complexity of computing x is given by

i = 0 O ( log n ) ( 2 i O ( log x ) ) k = O ( ( n log x ) k ) . {\displaystyle \sum \limits _{i=0}^{O(\log n)}{\big (}2^{i}O(\log x){\big )}^{k}=O{\big (}(n\log x)^{k}{\big )}.}

2-ary method

This algorithm calculates the value of x after expanding the exponent in base 2. It was first proposed by Brauer 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 with u odd.

Algorithm:

Input
An element x of G, a parameter k > 0, a non-negative integer n = (nl−1, nl−2, ..., n0)2 and the precomputed values x 3 , x 5 , . . . , x 2 k 1 {\displaystyle x^{3},x^{5},...,x^{2^{k}-1}} .
Output
The element x in G
y := 1; i := l - 1
while i ≥ 0 do
    (s, u) := f(ni)
    for j := 1 to k - s do
        y := y
    y := y * x
    for j := 1 to s do
        y := y
    i := i - 1
return y

For optimal efficiency, k should be the smallest integer satisfying

lg n < k ( k + 1 ) 2 2 k 2 k + 1 k 2 + 1. {\displaystyle \lg n<{\frac {k(k+1)\cdot 2^{2k}}{2^{k+1}-k-2}}+1.}

Sliding-window method

This method is an efficient variant of the 2-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-ary method algorithm and calculate 1, x, x, x, x, x, x, x, x, x, x, x. But, we can also compute 1, x, x, x, x, x, x, x, x, x, 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 n=(nl−1, nl−2, ..., n0)2, a parameter k > 0 and the pre-computed values x 3 , x 5 , . . . , x 2 k 1 {\displaystyle x^{3},x^{5},...,x^{2^{k}-1}} .
Output
The element xG.

Algorithm:

y := 1; i := l - 1
while i > -1 do
    if ni = 0 then
        y := y' i := i - 1
    else
        s := max{i - k + 1, 0}
        while ns = 0 do
            s := s + 1
        for h := 1 to i - s + 1 do
            y := y
        u := (ni, ni-1, ..., ns)2
        y := y * x
        i := s - 1
return y

Montgomery's ladder technique

Many algorithms for exponentiation do not provide defence against side-channel attacks. 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 of a positive, non-zero integer n = (nk−1...n0)2 with nk−1 = 1, we can compute x as follows:

x1 = x; x2 = x
for i = k - 2 to 0 do
    if ni = 0 then
        x2 = x1 * x2; x1 = x1
    else
        x1 = x1 * x2; x2 = x2
return x1

The algorithm performs a fixed sequence of operations (up to 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 attacks: 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 when the base is fixed and the exponent varies. As one can see, precomputations play a key role in these algorithms.

Yao's method

Yao's method is orthogonal to the 2-ary method where the exponent is expanded in radix b = 2 and the computation is as performed in the algorithm above. Let n, ni, b, and bi be integers.

Let the exponent n be written as

n = i = 0 w 1 n i b i , {\displaystyle n=\sum _{i=0}^{w-1}n_{i}b_{i},}

where 0 n i < h {\displaystyle 0\leqslant n_{i}<h} for all i [ 0 , w 1 ] {\displaystyle i\in } .

Let xi = x.

Then the algorithm uses the equality

x n = i = 0 w 1 x i n i = j = 1 h 1 [ n i = j x i ] j . {\displaystyle x^{n}=\prod _{i=0}^{w-1}x_{i}^{n_{i}}=\prod _{j=1}^{h-1}{\bigg }^{j}.}

Given the element x of G, and the exponent n written in the above form, along with the precomputed values x...x, the element x is calculated using the algorithm below:

y = 1, u = 1, j = h - 1
while j > 0 do
    for i = 0 to w - 1 do
        if ni = j then
            u = u × x
    y = y × u
    j = j - 1
return y

If we set h = 2 and bi = h, then the ni values are simply the digits of n in base h. Yao's method collects in u first those xi that appear to the highest power ⁠ h 1 {\displaystyle h-1} ⁠; in the next round those with power ⁠ h 2 {\displaystyle h-2} ⁠ are collected in u as well etc. The variable y is multiplied ⁠ h 1 {\displaystyle h-1} ⁠ times with the initial u, ⁠ h 2 {\displaystyle h-2} ⁠ times with the next highest powers, and so on. The algorithm uses ⁠ w + h 2 {\displaystyle w+h-2} ⁠ multiplications, and ⁠ w + 1 {\displaystyle w+1} ⁠ elements must be stored to compute x.

Euclidean method

The Euclidean method was first introduced in Efficient exponentiation using precomputation and vector addition chains by P.D Rooij.

This method for computing x n {\displaystyle x^{n}} in group G, where n is a natural integer, whose algorithm is given below, is using the following equality recursively:

x 0 n 0 x 1 n 1 = ( x 0 x 1 q ) n 0 x 1 n 1 mod n 0 , {\displaystyle x_{0}^{n_{0}}\cdot x_{1}^{n_{1}}=\left(x_{0}\cdot x_{1}^{q}\right)^{n_{0}}\cdot x_{1}^{n_{1}\mod n_{0}},}

where q = n 1 n 0 {\displaystyle q=\left\lfloor {\frac {n_{1}}{n_{0}}}\right\rfloor } . In other words, a Euclidean division of the exponent n1 by n0 is used to return a quotient q and a rest n1 mod n0.

Given the base element x in group G, and the exponent n {\displaystyle n} written as in Yao's method, the element x n {\displaystyle x^{n}} is calculated using l {\displaystyle l} precomputed values x b 0 , . . . , x b l i {\displaystyle x^{b_{0}},...,x^{b_{l_{i}}}} and then the algorithm below.

Begin loop
    Find 
  
    
      
        M
        
        [
        0
        ,
        l
        
        1
        ]
      
    
    {\displaystyle M\in }
  
, such that 
  
    
      
        
        i
        
        [
        0
        ,
        l
        
        1
        ]
        ,
        
          n
          
            M
          
        
        
        
          n
          
            i
          
        
      
    
    {\displaystyle \forall i\in ,n_{M}\geq n_{i}}
  
.
    Find 
  
    
      
        N
        
        
          
            (
          
        
        [
        0
        ,
        l
        
        1
        ]
        
        M
        
          
            )
          
        
      
    
    {\displaystyle N\in {\big (}-M{\big )}}
  
, such that 
  
    
      
        
        i
        
        
          
            (
          
        
        [
        0
        ,
        l
        
        1
        ]
        
        M
        
          
            )
          
        
        ,
        
          n
          
            N
          
        
        
        
          n
          
            i
          
        
      
    
    {\displaystyle \forall i\in {\big (}-M{\big )},n_{N}\geq n_{i}}
  
.
    Break loop if 
  
    
      
        
          n
          
            N
          
        
        =
        0
      
    
    {\displaystyle n_{N}=0}
  
.
    Let 
  
    
      
        q
        =
        
        
          n
          
            M
          
        
        
          /
        
        
          n
          
            N
          
        
        
      
    
    {\displaystyle q=\lfloor n_{M}/n_{N}\rfloor }
  
, and then let 
  
    
      
        
          n
          
            N
          
        
        =
        (
        
          n
          
            M
          
        
        
          
            mod
            
              n
            
          
          
            N
          
        
        )
      
    
    {\displaystyle n_{N}=(n_{M}{\bmod {n}}_{N})}
  
.
    Compute recursively 
  
    
      
        
          x
          
            M
          
          
            q
          
        
      
    
    {\displaystyle x_{M}^{q}}
  
, and then let 
  
    
      
        
          x
          
            N
          
        
        =
        
          x
          
            N
          
        
        
        
          x
          
            M
          
          
            q
          
        
      
    
    {\displaystyle x_{N}=x_{N}\cdot x_{M}^{q}}
  
.
End loop;
Return 
  
    
      
        
          x
          
            n
          
        
        =
        
          x
          
            M
          
          
            
              n
              
                M
              
            
          
        
      
    
    {\displaystyle x^{n}=x_{M}^{n_{M}}}
  
.

The algorithm first finds the largest value among the ni and then the supremum within the set of { ni \ iM }. Then it raises xM to the power q, multiplies this value with xN, and then assigns xN the result of this computation and nM the value nM modulo nN.

Further applications

The approach also works with semigroups that are not of characteristic zero, for example allowing fast computation of large exponents modulo a number. Especially in cryptography, it is useful to compute powers in a ring of integers modulo q. For example, the evaluation of

13789 (mod 2345) = 2029

would take a very long time and much storage space if the naïve method of computing 13789 and then taking the remainder when divided by 2345 were used. Even using a more effective method will take a long time: square 13789, take the remainder when divided by 2345, multiply the result by 13789, and so on.

Applying above exp-by-squaring algorithm, with "*" interpreted as x * y = xy mod 2345 (that is, a multiplication followed by a division with remainder) leads to only 27 multiplications and divisions of integers, which may all be stored in a single machine word. Generally, any of these approaches will take fewer than 2log2(722340) ≤ 40 modular multiplications.

The approach can also be used to compute integer powers in a group, using either of the rules

Power(x, −n) = Power(x, n),
Power(x, −n) = (Power(x, n)).

The approach also works in non-commutative semigroups and is often used to compute powers of matrices.

More generally, the approach works with positive integer exponents in every magma for which the binary operation is power associative.

Signed-digit recoding

In certain computations it may be more efficient to allow negative coefficients and hence use the inverse of the base, provided inversion in G is "fast" or has been precomputed. For example, when computing x, the binary method requires k−1 multiplications and k−1 squarings. However, one could perform k squarings to get x and then multiply by x to obtain x.

To this end we define the signed-digit representation of an integer n in radix b as

n = i = 0 l 1 n i b i  with  | n i | < b . {\displaystyle n=\sum _{i=0}^{l-1}n_{i}b^{i}{\text{ with }}|n_{i}|<b.}

Signed binary representation corresponds to the particular choice b = 2 and n i { 1 , 0 , 1 } {\displaystyle n_{i}\in \{-1,0,1\}} . It is denoted by ( n l 1 n 0 ) s {\displaystyle (n_{l-1}\dots n_{0})_{s}} . There are several methods for computing this representation. The representation is not unique. For example, take n = 478: two distinct signed-binary representations are given by ( 10 1 ¯ 1100 1 ¯ 10 ) s {\displaystyle (10{\bar {1}}1100{\bar {1}}10)_{s}} and ( 100 1 ¯ 1000 1 ¯ 0 ) s {\displaystyle (100{\bar {1}}1000{\bar {1}}0)_{s}} , where 1 ¯ {\displaystyle {\bar {1}}} is used to denote −1. Since the binary method computes a multiplication for every non-zero entry in the base-2 representation of n, we are interested in finding the signed-binary representation with the smallest number of non-zero entries, that is, the one with minimal Hamming weight. One method of doing this is to compute the representation in non-adjacent form, or NAF for short, which is one that satisfies n i n i + 1 = 0  for all  i 0 {\displaystyle n_{i}n_{i+1}=0{\text{ for all }}i\geqslant 0} and denoted by ( n l 1 n 0 ) NAF {\displaystyle (n_{l-1}\dots n_{0})_{\text{NAF}}} . For example, the NAF representation of 478 is ( 1000 1 ¯ 000 1 ¯ 0 ) NAF {\displaystyle (1000{\bar {1}}000{\bar {1}}0)_{\text{NAF}}} . This representation always has minimal Hamming weight. A simple algorithm to compute the NAF representation of a given integer n = ( n l n l 1 n 0 ) 2 {\displaystyle n=(n_{l}n_{l-1}\dots n_{0})_{2}} with n l = n l 1 = 0 {\displaystyle n_{l}=n_{l-1}=0} is the following:


  
    
      
        
          c
          
            0
          
        
        =
        0
      
    
    {\displaystyle c_{0}=0}
  

for i = 0 to l − 1 do
  
  
    
      
        
          c
          
            i
            +
            1
          
        
        =
        
          
          
            
              
                1
                2
              
            
            (
            
              c
              
                i
              
            
            +
            
              n
              
                i
              
            
            +
            
              n
              
                i
                +
                1
              
            
            )
          
          
        
      
    
    {\displaystyle c_{i+1}=\left\lfloor {\frac {1}{2}}(c_{i}+n_{i}+n_{i+1})\right\rfloor }
  

  
  
    
      
        
          n
          
            i
          
          
        
        =
        
          c
          
            i
          
        
        +
        
          n
          
            i
          
        
        
        2
        
          c
          
            i
            +
            1
          
        
      
    
    {\displaystyle n_{i}'=c_{i}+n_{i}-2c_{i+1}}
  

return 
  
    
      
        (
        
          n
          
            l
            
            1
          
          
        
        
        
          n
          
            0
          
          
        
        
          )
          
            NAF
          
        
      
    
    {\displaystyle (n_{l-1}'\dots n_{0}')_{\text{NAF}}}
  

Another algorithm by Koyama and Tsuruoka does not require the condition that n i = n i + 1 = 0 {\displaystyle n_{i}=n_{i+1}=0} ; it still minimizes the Hamming weight.

Alternatives and generalizations

Main article: Addition-chain exponentiation

Exponentiation by squaring can be viewed as a suboptimal addition-chain exponentiation algorithm: it computes the exponent by an addition chain consisting of repeated exponent doublings (squarings) and/or incrementing exponents by one (multiplying by x) only. More generally, if one allows any previously computed exponents to be summed (by multiplying those powers of x), one can sometimes perform the exponentiation using fewer multiplications (but typically using more memory). The smallest power where this occurs is for n = 15:

x 15 = x × ( x × [ x × x 2 ] 2 ) 2 {\displaystyle x^{15}=x\times (x\times ^{2})^{2}}  (squaring, 6 multiplies),
x 15 = x 3 × ( [ x 3 ] 2 ) 2 {\displaystyle x^{15}=x^{3}\times (^{2})^{2}}  (optimal addition chain, 5 multiplies if x is re-used).

In general, finding the optimal addition chain for a given exponent is a hard problem, for which no efficient algorithms are known, so optimal chains are typically used for small exponents only (e.g. in compilers where the chains for small powers have been pre-tabulated). However, there are a number of heuristic algorithms that, while not being optimal, have fewer multiplications than exponentiation by squaring at the cost of additional bookkeeping work and memory usage. Regardless, the number of multiplications never grows more slowly than Θ(log n), so these algorithms improve asymptotically upon exponentiation by squaring by only a constant factor at best.

See also

Notes

  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 x 2 k 1 {\displaystyle x^{2^{k}-1}} need be computed, and only those specifically involved in the computation need be considered.

References

  1. ^ Cohen, H.; Frey, G., eds. (2006). Handbook of Elliptic and Hyperelliptic Curve Cryptography. Discrete Mathematics and Its Applications. Chapman & Hall/CRC. ISBN 9781584885184.
  2. Montgomery, Peter L. (1987). "Speeding the Pollard and Elliptic Curve Methods of Factorization" (PDF). Math. Comput. 48 (177): 243–264. doi:10.1090/S0025-5718-1987-0866113-7.
  3. Gueron, Shay (5 April 2012). "Efficient software implementations of modular exponentiation" (PDF). Journal of Cryptographic Engineering. 2 (1): 31–43. doi:10.1007/s13389-012-0031-5. S2CID 7629541.
Categories: