Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Exponentiation by squaring

From Wikipedia, the free encyclopedia
Algorithm for fast exponentiation
icon
This articleneeds additional citations forverification. Please helpimprove this article byadding 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)

Inmathematics andcomputer programming,exponentiating by squaring is a general method for fast computation of largepositive integer powers of anumber, or more generally of an element of asemigroup, like apolynomial or asquare matrix. Some variants are commonly referred to assquare-and-multiply algorithms orbinary exponentiation. These can be of quite general use, for example inmodular arithmetic or powering of matrices. For semigroups for whichadditive notation is commonly used, likeelliptic curves used incryptography, this method is also referred to asdouble-and-add.

Basic method

[edit]

Recursive version

[edit]

The method is based on the observation that, for any integern>0{\displaystyle n>0}, one hasxn={x(x2)(n1)/2if n is odd,(x2)n/2if n is even.{\displaystyle x^{n}={\begin{cases}x\,(x^{2})^{(n-1)/2}&{\text{if }}n{\text{ is odd}},\\(x^{2})^{n/2}&{\text{if }}n{\text{ is even}}.\end{cases}}}

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

Together, these may be implemented directly as the followingrecursive algorithm:

Inputs: a real numberx; an integernOutput:xnfunction exp_by_squaring(x,n)isifn < 0thenreturn exp_by_squaring(1 /x, −n)else ifn = 0thenreturn 1else ifn is eventhenreturn exp_by_squaring(x ×x,n / 2)else ifn is oddthenreturnx × exp_by_squaring(x ×x, (n − 1) / 2)end function

In each recursive call, the least-significant digit of thebinary representation ofn is removed. It follows that the number of recursive calls islog2n,{\displaystyle \lceil \log _{2}n\rceil ,} the number ofbits of the binary representation ofn. So this algorithm computes this number of squares and a lower number of multiplication, which is equal to the number of 1s in the binary representation ofn. This logarithmic number of operations is to be compared with the trivial algorithm which requiresn − 1 multiplications.

This algorithm is nottail-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

[edit]

The variants described in this section are based on the formulayxn={yx(x2)(n1)/2if n is odd,y(x2)n/2if n is even.{\displaystyle yx^{n}={\begin{cases}yx\,(x^{2})^{(n-1)/2}&{\text{if }}n{\text{ is odd}},\\y\,(x^{2})^{n/2}&{\text{if }}n{\text{ is even}}.\end{cases}}}

If one applies recursively this formula, by starting withy = 1, one gets eventually an exponent equal to0, and the desired result is then the left factor.

This may be implemented as a tail-recursive function:

Functionexp_by_squaring(x,n)returnexp_by_squaring2(1,x,n)Functionexp_by_squaring2(y,x,n)ifn<0thenreturnexp_by_squaring2(y,1/x,-n);elseifn=0thenreturny;elseifniseventhenreturnexp_by_squaring2(y,x*x,n/2);elseifnisoddthenreturnexp_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

Functionexp_by_squaring_iterative(x,n)ifn<0thenx:=1/x;n:=-n;ifn=0thenreturn1y:=1;whilen>1doifnisoddtheny:=x*y;n:=n-1;x:=x*x;n:=n/2;returnx*y

The correctness of the algorithm results from the fact thatyxn{\displaystyle yx^{n}} is invariant during the computation; it is1xn=xn{\displaystyle 1\cdot x^{n}=x^{n}} at the beginning; and it isyx1=xy{\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

[edit]

A brief analysis shows that such an algorithm useslog2n{\displaystyle \lfloor \log _{2}n\rfloor } squarings and at mostlog2n{\displaystyle \lfloor \log _{2}n\rfloor } multiplications, where{\displaystyle \lfloor \;\rfloor } denotes thefloor function. More precisely, the number of multiplications is one less than the number of ones present in thebinary expansion ofn. Forn 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 twod-digit numbers is implemented in O(dk) operations for some fixedk, then the complexity of computingxn is given by

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

2k-ary method

[edit]

This algorithm calculates the value ofxn after expanding the exponent in base 2k. It was first proposed byBrauer in 1939. In the algorithm below we make use of the following functionf(0) = (k, 0) andf(m) = (s, u), wherem =u·2s withu odd.

Algorithm:

Input
An elementx ofG, a parameterk > 0, a non-negative integern = (nl−1,nl−2, ...,n0)2k and the precomputed valuesx3,x5,...,x2k1{\displaystyle x^{3},x^{5},...,x^{2^{k}-1}}.
Output
The elementxn inG
y := 1; i := l - 1while i ≥ 0 do    (s, u) := f(ni)for j := 1to k - sdo        y := y2    y := y * xufor j := 1to sdo        y := y2    i := i - 1return y

For optimal efficiency,k should be the smallest integer satisfying[1]

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

Sliding-window method

[edit]

This method is an efficient variant of the 2k-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 2k-ary method algorithm and calculate 1, x3, x6, x12, x24, x48, x49, x98, x99, x198, x199, x398.But, we can also compute 1, x3, x6, x12, x24, x48, x96, x192, x199, x398, which saves one multiplication and amounts to evaluating (110 001 110)2

Here is the general algorithm:

Algorithm:

Input
An elementx ofG, a non negative integern=(nl−1,nl−2, ...,n0)2, a parameterk > 0 and the pre-computed valuesx3,x5,...,x2k1{\displaystyle x^{3},x^{5},...,x^{2^{k}-1}}.
Output
The elementxnG.

Algorithm:

y := 1; i := l - 1while i > -1doif ni = 0then        y := y2        i := i - 1else        s := max{i - k + 1, 0}while ns = 0do            s := s + 1[notes 1]for h := 1to i - s + 1do            y := y2        u := (ni, ni-1, ..., ns)2        y := y * xu        i := s - 1return y

Montgomery's ladder technique

[edit]

Many algorithms for exponentiation do not provide defence againstside-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 manypublic-key cryptosystems. A technique called "Montgomery's ladder"[2] addresses this concern.

Given thebinary expansion of a positive, non-zero integern = (nk−1...n0)2 withnk−1 = 1, we can computexn as follows:

x1 = x; x2 = x2for i = k - 2 to 0doif ni = 0then        x2 = x1 * x2; x1 = x12else        x1 = x1 * x2; x2 = x22return 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 cachetiming 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.[3]

Fixed-base exponent

[edit]

There are several methods which can be employed to calculatexn when the base is fixed and the exponent varies. As one can see,precomputations play a key role in these algorithms.

Yao's method

[edit]

Yao's method is orthogonal to the2k-ary method where the exponent is expanded in radixb = 2k and the computation is as performed in the algorithm above. Letn,ni,b, andbi be integers.

Let the exponentn be written as

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

where0ni<h{\displaystyle 0\leqslant n_{i}<h} for alli[0,w1]{\displaystyle i\in [0,w-1]}.

Letxi =xbi.

Then the algorithm uses the equality

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

Given the elementx ofG, and the exponentn written in the above form, along with the precomputed valuesxb0...xbw−1, the elementxn is calculated using the algorithm below:

y = 1, u = 1, j = h - 1while j > 0dofor i = 0to w - 1doif ni = jthen            u = u × xbi    y = y × u    j = j - 1return y

If we seth = 2k andbi =hi, then theni values are simply the digits ofn in baseh. Yao's method collects inu first thosexi that appear to the highest powerh1{\displaystyle h-1}; in the next round those with powerh2{\displaystyle h-2} are collected inu as well etc. The variabley is multipliedh1{\displaystyle h-1} times with the initialu,h2{\displaystyle h-2} times with the next highest powers, and so on.The algorithm usesw+h2{\displaystyle w+h-2} multiplications, andw+1{\displaystyle w+1} elements must be stored to computexn.[1]

Euclidean method

[edit]

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

This method for computingxn{\displaystyle x^{n}} in groupG, wheren is a natural integer, whose algorithm is given below, is using the following equality recursively:

x0n0x1n1=(x0x1q)n0x1n1modn0,{\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}},}

whereq=n1n0{\displaystyle q=\left\lfloor {\frac {n_{1}}{n_{0}}}\right\rfloor }.In other words, a Euclidean division of the exponentn1 byn0 is used to return a quotientq and a restn1 modn0.

Given the base elementx in groupG, and the exponentn{\displaystyle n} written as in Yao's method, the elementxn{\displaystyle x^{n}} is calculated usingl{\displaystyle l} precomputed valuesxb0,...,xbli{\displaystyle x^{b_{0}},...,x^{b_{l_{i}}}} and then the algorithm below.

Begin loopFindM[0,l1]{\displaystyle M\in [0,l-1]},such thati[0,l1],nMni{\displaystyle \forall i\in [0,l-1],n_{M}\geq n_{i}}.FindN([0,l1]M){\displaystyle N\in {\big (}[0,l-1]-M{\big )}},such thati([0,l1]M),nNni{\displaystyle \forall i\in {\big (}[0,l-1]-M{\big )},n_{N}\geq n_{i}}.Break loopifnN=0{\displaystyle n_{N}=0}.Letq=nM/nN{\displaystyle q=\lfloor n_{M}/n_{N}\rfloor },and thenletnN=(nMmodnN){\displaystyle n_{N}=(n_{M}{\bmod {n}}_{N})}.Compute recursivelyxMq{\displaystyle x_{M}^{q}},and thenletxN=xNxMq{\displaystyle x_{N}=x_{N}\cdot x_{M}^{q}}.End loop;Returnxn=xMnM{\displaystyle x^{n}=x_{M}^{n_{M}}}.

The algorithm first finds the largest value among theni and then thesupremum within the set of{ni \iM }.Then it raisesxM to the powerq, multiplies this value withxN, and then assignsxN the result of this computation andnM the valuenM modulonN.

Further applications

[edit]

The approach also works withsemigroups that are not ofcharacteristic zero, for example allowing fast computation of largeexponents modulo a number. Especially incryptography, it is useful to compute powers in aring ofintegers moduloq. For example, the evaluation of

13789722341 (mod 2345) = 2029

would take a very long time and much storage space if the naïve method of computing13789722341 and then taking theremainder 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 theresult by 13789, and so on.

Applying aboveexp-by-squaring algorithm, with "*" interpreted asx *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 than2log2(722340) ≤ 40 modular multiplications.

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

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

The approach also works innon-commutative semigroups and is often used to compute powers ofmatrices.

More generally, the approach works with positive integer exponents in everymagma for which thebinary operation ispower associative.

Signed-digit recoding

[edit]

In certain computations it may be more efficient to allow negative coefficients and hence use the inverse of the base, provided inversion inG is "fast" or has been precomputed. For example, when computingx2k−1, the binary method requiresk−1 multiplications andk−1 squarings. However, one could performk squarings to getx2k and then multiply byx−1 to obtainx2k−1.

To this end we define thesigned-digit representation of an integern in radixb as

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

Signed binary representation corresponds to the particular choiceb = 2 andni{1,0,1}{\displaystyle n_{i}\in \{-1,0,1\}}. It is denoted by(nl1n0)s{\displaystyle (n_{l-1}\dots n_{0})_{s}}. There are several methods for computing this representation. The representation is not unique. For example, taken = 478: two distinct signed-binary representations are given by(101¯11001¯10)s{\displaystyle (10{\bar {1}}1100{\bar {1}}10)_{s}} and(1001¯10001¯0)s{\displaystyle (100{\bar {1}}1000{\bar {1}}0)_{s}}, where1¯{\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 ofn, we are interested in finding the signed-binary representation with the smallest number of non-zero entries, that is, the one withminimalHamming weight. One method of doing this is to compute the representation innon-adjacent form, or NAF for short, which is one that satisfiesnini+1=0 for all i0{\displaystyle n_{i}n_{i+1}=0{\text{ for all }}i\geqslant 0} and denoted by(nl1n0)NAF{\displaystyle (n_{l-1}\dots n_{0})_{\text{NAF}}}. For example, the NAF representation of 478 is(10001¯0001¯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 integern=(nlnl1n0)2{\displaystyle n=(n_{l}n_{l-1}\dots n_{0})_{2}} withnl=nl1=0{\displaystyle n_{l}=n_{l-1}=0} is the following:

c0=0{\displaystyle c_{0}=0}fori = 0 tol − 1 doci+1=12(ci+ni+ni+1){\displaystyle c_{i+1}=\left\lfloor {\frac {1}{2}}(c_{i}+n_{i}+n_{i+1})\right\rfloor }ni=ci+ni2ci+1{\displaystyle n_{i}'=c_{i}+n_{i}-2c_{i+1}}return(nl1n0)NAF{\displaystyle (n_{l-1}'\dots n_{0}')_{\text{NAF}}}

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

Alternatives and generalizations

[edit]
Main article:Addition-chain exponentiation

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

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

In general, finding theoptimal 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. incompilers where the chains for small powers have been pre-tabulated). However, there are a number ofheuristic 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Θ(logn), so these algorithms improve asymptotically upon exponentiation by squaring by only a constant factor at best.

See also

[edit]

Notes

[edit]
  1. ^In this line, the loop finds the longest string of length less than or equal tok ending in a non-zero value. Not all odd powers of 2 up tox2k1{\displaystyle x^{2^{k}-1}} need be computed, and only those specifically involved in the computation need be considered.

References

[edit]
  1. ^abCohen, 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.
Retrieved from "https://en.wikipedia.org/w/index.php?title=Exponentiation_by_squaring&oldid=1317159776"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp