Salta al contenuto
Note per Studenti Fast Exponentiation by Repeated Squaring Report

Fast Exponentiation by Repeated Squaring

In questa pagina 5

Let DD be a domain and ∘:D×D→D\circ:D\times D\to D an associative operator, (a∘b)∘c=a∘(b∘c)(a\circ b)\circ c=a\circ(b\circ c), with identity ee (a∘e=e∘a=aa\circ e=e\circ a=a). Examples: (N,+)(\mathbb N,+) with e=0e=0; n×nn\times n matrices with the row-by-column product, e=Ine=I_n. ∘\circ need not be commutative.

Definition (power). xn=ex^n=e for n=0n=0; xn=x∘xn−1=xn−1∘xx^n=x\circ x^{n-1}=x^{n-1}\circ x for n>0n>0 (by associativity the two forms agree, also for non-commutative ∘\circ).

Cost model: 11 per application of ∘\circ, 00 for the rest.

Definition-based algorithm

STUPID_POWER(x, n)
  if n = 0 then return e
  p <- x
  for i <- 1 to n - 1 do
    p <- x ∘ p
  return p

TSP(n)=n−1=Θ(n)T_{SP}(n)=n-1=\Theta(n): linear in the exponent. We want better.

Substructure

Property. With k=⌊n2⌋k=\lfloor\frac n2\rfloor: if n=2kn=2k then xn=xk∘xkx^n=x^k\circ x^k; if n=2k+1n=2k+1 then xn=xk∘xk∘xx^n=x^k\circ x^k\circ x.

Proof. xk+kx^{k+k} and xk+k+1x^{k+k+1}, grouping the factors by associativity; no other hypothesis on ∘\circ. ■\blacksquare

Given y=x⌊n/2⌋y=x^{\lfloor n/2\rfloor}, one application of ∘\circ if nn is even (y∘yy\circ y), two if odd (y∘y∘xy\circ y\circ x). Algorithms of this kind are called squaring algorithms.

Recursive algorithm POWER

POWER(x, n)
  if n = 0 then return e                { BASE }
  if n = 1 then return x
  k <- floor(n / 2)                     { DIVIDE: no work }
  y <- POWER(x, k)                      { RECURSE }
  if EVEN(n) then return y ∘ y          { CONQUER }
  else return y ∘ y ∘ x

The base case n=1n=1 is superfluous but avoids two useless applications (e∘e∘xe\circ e\circ x). Correctness follows from the substructure property.

Analysis

Conquer costs at most 22, Divide 00: T(n)≤{0n=0,1T(⌊n2⌋)+2n>1.T(n)\le\begin{cases}0&n=0,1\\T(\lfloor\frac n2\rfloor)+2&n>1.\end{cases} For n=2t−1n=2^t-1 every generated instance is odd, so 22 is paid at every level (the bound is attained). The recurrence has a=1a=1, b=2b=2, w=2w=2: threshold n0=1=Θ(w)n^0=1=\Theta(w), Case 2 of the Master TheoremThe Master Theorem for T(n) = aT(n/b) + w(n) compares w(n) with the threshold n^(log_b a). Case 1 (w polynomially smaller): Theta(n^(log_b a)); case 2 (same order): Theta(n^(log_b a) log n); case 3 (polynomially larger and regular): Theta(w(n)). Full proof from the levels of the tree, extended version with floors and ceilings, a table of applications, and the misuse when no case applies (w = n log n).Master Theorem →, so T(n)=Θ(log⁡n)T(n)=\Theta(\log n) (same recurrence as binary search): an exponential improvement over STUPID_POWER.

Exact count. Let ν(n)\nu(n) be the number of 11 bits of nn. For n≥1n\ge1: TPOWER(n)=⌊log⁡2n⌋+ν(n)−1.T_{POWER}(n)=\lfloor\log_2n\rfloor+\nu(n)-1. Proof (induction on nn). n=1n=1: 0+1−1=00+1-1=0. For even n≥2n\ge2: T(n)=T(n2)+1T(n)=T(\frac n2)+1, with ⌊log⁡2n2⌋=⌊log⁡2n⌋−1\lfloor\log_2\frac n2\rfloor=\lfloor\log_2n\rfloor-1 and ν(n2)=ν(n)\nu(\frac n2)=\nu(n), so T(n)=⌊log⁡2n⌋+ν(n)−1T(n)=\lfloor\log_2n\rfloor+\nu(n)-1. For odd n≥3n\ge3: T(n)=T(n−12)+2T(n)=T(\frac{n-1}2)+2 with ⌊log⁡2n−12⌋=⌊log⁡2n⌋−1\lfloor\log_2\frac{n-1}2\rfloor=\lfloor\log_2n\rfloor-1 and ν(n−12)=ν(n)−1\nu(\frac{n-1}2)=\nu(n)-1: (⌊log⁡2n⌋−1)+(ν(n)−1)−1+2=⌊log⁡2n⌋+ν(n)−1(\lfloor\log_2n\rfloor-1)+(\nu(n)-1)-1+2=\lfloor\log_2n\rfloor+\nu(n)-1. ■\blacksquare

That is ⌊log⁡2n⌋\lfloor\log_2n\rfloor squarings (one per level) plus ν(n)−1\nu(n)-1 multiplications by xx. On 2k≤n<2k+12^k\le n<2^{k+1} the minimum is kk (n=2kn=2^k) and the maximum 2k2k (n=2k+1−1n=2^{k+1}-1). For n=2tn=2^t the general formula with s=1s=1, w=1w=1 gives log⁡2n\log_2n.

Example (x13x^{13}). 13→6→3→113\to6\to3\to1: POWER(x,3) =x∘x∘x=x\circ x\circ x (2 operations), POWER(x,6) =y∘y=y\circ y (1), POWER(x,13) =y∘y∘x=y\circ y\circ x (2). Total 5=3+3−15=3+3-1, against 1212 for STUPID_POWER.

Cost-model remark. Unit cost is reasonable for sums and products of integers or reals, not for operators whose results are larger than the operands (set union, polynomial product, integers with huge numbers of digits): there the analysis needs an adequate cost model.

Iterative algorithms

With n=bkbk−1…b0n=b_kb_{k-1}\dots b_0 in binary, k=⌊log⁡2n⌋k=\lfloor\log_2n\rfloor, associativity gives xn=∘bi=1 x2ix^n=\circ_{b_i=1}\,x^{2^i}, and x2i=x2i−1∘x2i−1x^{2^i}=x^{2^{i-1}}\circ x^{2^{i-1}}.

POWER2(x, n)
  if n = 0 then return e
  * n = b_k b_{k-1} ... b_0 *
  p <- e                         { accumulates the powers x^(2^i) with b_i = 1 }
  s <- x                         { at the start of iteration i: s = x^(2^i) }
  for i <- 0 to k do
    if b_i = 1 then p <- p ∘ s
    s <- s ∘ s
  return p

Literal count: k+1k+1 squarings and ν(n)\nu(n) products: TPOWER2(n)=k+1+ν(n)≤2(⌊log⁡2n⌋+1)T_{POWER2}(n)=k+1+\nu(n)\le2(\lfloor\log_2n\rfloor+1), Θ(log⁡n)\Theta(\log n).

The bits are not needed: use the parity test and integer division with m←nm\leftarrow n:

POWER3(x, n)
  p <- e;  s <- x;  m <- n
  for i <- 0 to k do
    if NOT EVEN(m) then p <- p ∘ s
    s <- s ∘ s
    m <- floor(m / 2)
  return p

POWER3 performs the same operations as POWER, bottom-up: only the Conquer phases, skipping the top-down generation of the tree.

ii bib_i pp after the step ss after the step
0 1 e∘x=xe\circ x=x x2x^2
1 0 xx x4x^4
2 1 x∘x4=x5x\circ x^4=x^5 x8x^8
3 1 x5∘x8=x13x^5\circ x^8=x^{13} x16x^{16} (useless)

Precise count. Literally, POWER3 performs k+1+ν(n)=TPOWER(n)+2k+1+\nu(n)=T_{POWER}(n)+2 applications (for n=13n=13: 77 versus 55): the first p∘sp\circ s with p=ep=e produces nothing new, and the last squaring computes an unused power. With two optimizations (start from p←sp\leftarrow s at the first 11 bit, do not square after the last bit) the counts coincide.

Example with matrices: Fibonacci numbers

With ∘\circ the product of 2×22\times2 matrices and M=(1110)M=\begin{pmatrix}1&1\\1&0\end{pmatrix}: Mn=(Fn+1FnFnFn−1)M^n=\begin{pmatrix}F_{n+1}&F_n\\F_n&F_{n-1}\end{pmatrix} (induction, Mn+1=MnMM^{n+1}=M^nM). For n=13n=13: M→M2→M3→M6→M13=(377233233144)M\to M^2\to M^3\to M^6\to M^{13}=\begin{pmatrix}377&233\\233&144\end{pmatrix}, so F13=233F_{13}=233. Θ(log⁡n)\Theta(\log n) products of 2×22\times2 matrices give FnF_n (compare with recursion and memoization in dynamic programming). Caution: FnF_n has Θ(n)\Theta(n) bits, so scalar operations are not unit cost for large nn. For general matrices, AmA^m needs Θ(log⁡m)\Theta(\log m) products, each 2n3−n22n^3-n^2 scalar operations (Matrix Multiplication - Iterative and Recursive Block ProductCost model on n x n matrices (scalar operations, size n or N = n^2); sum in n^2 operations (optimal); iterative row-by-column product with exact cost 2n^3 - n^2; the fractal property of the block product proved on indices; recursive algorithm RMUL with T(n) = 8T(n/2) + n^2, Theta(n^3) and exact solution 2n^3 - n^2: it performs the same operations as the iterative one.Matrix Multiplication - Iterative and Recursive Block Product →) or fewer with Strassen's AlgorithmStrassen computes the n x n product with 7 recursive calls instead of 8, using 10 matrix additions in Divide and 8 in Conquer: T(n) = 7T(n/2) + (9/2)n^2, Theta(n^(log2 7)) with exact solution 7n^(log2 7) - 6n^2. Its leading constant 7 is more than three times that of the iterative algorithm (2), so Strassen beats it only from n = 655 (from 1024 for powers of two).Strassen's Algorithm →; for structured (circulant) matrices the product is cheaper (Supercirculant and Circulant MatricesSupercirculant matrices (alternating recursive quadrants) have only n distinct values: sum in n operations, product in 4n log2 n + n with the trick (A1+A2)(B1+B2) and (A1-A2)(B1-B2) instead of 4 calls (Theta(n^2)); their eigenvalues are the Hadamard transform of the first row (FHT, n log2 n). Circulant matrices are polynomials in the rotation matrix R, their product is the cyclic convolution of the first rows, and the Fourier matrix diagonalizes them: product in O(n log n) with the FFT.Supercirculant and Circulant Matrices →). The same scheme applied to polynomials, with convolution as ∘\circ: Notable Transforms and Polynomial ExponentiationSome vector families have a known or cheaper DFT than the general FFT: the constant vector (a,...,a) has DFT (na,0,...,0), the vector (a,0,...,0) has DFT (a,...,a); an (n,k)-sparse vector has a DFT made of k copies of the DFT_{n/k} of its components at multiples of k, and SPARSE_FFT costs 2 (n/k) log2(n/k) with recurrence T(n,k) = T(n/2,k/2). For the power p(x)^k of a polynomial with n coefficients: either repeated squaring with LIN_CONV, O(nk log(nk)), or evaluate p with the FFT on h = 2^ceil(log2((n-1)k+1)) points, raise each value to the k, and invert, Theta(nk log(nk)).Notable Transforms and Polynomial Exponentiation →.

Versione ripasso

  • Setting: ∘\circ associative with identity ee (non-commutative allowed, e.g. matrix product with e=Ine=I_n); x0=ex^0=e, xn=x∘xn−1=xn−1∘xx^n=x\circ x^{n-1}=x^{n-1}\circ x. Cost = number of applications of ∘\circ.
  • STUPID_POWER: p←xp\leftarrow x, then n−1n-1 times p←x∘pp\leftarrow x\circ p: T=n−1=Θ(n)T=n-1=\Theta(n).
  • Substructure: k=⌊n2⌋k=\lfloor\frac n2\rfloor; xn=xk∘xkx^n=x^k\circ x^k (nn even), xn=xk∘xk∘xx^n=x^k\circ x^k\circ x (nn odd). Proof: xk+kx^{k+k}, xk+k+1x^{k+k+1} grouped by associativity. From y=xky=x^k: 11 application (even) or 22 (odd).
  • POWER: base n=0n=0 (ee), n=1n=1 (xx, avoids two useless applications); Divide 00; y←y\leftarrow POWER(x,k)(x,k); Conquer y∘yy\circ y or y∘y∘xy\circ y\circ x.
  • Recurrence: T(n)≤T(⌊n2⌋)+2T(n)\le T(\lfloor\frac n2\rfloor)+2, T(0)=T(1)=0T(0)=T(1)=0. a=1a=1, b=2b=2, w=2w=2, threshold n0=1n^0=1: Case 2, Θ(log⁡n)\Theta(\log n) (Master TheoremThe Master Theorem for T(n) = aT(n/b) + w(n) compares w(n) with the threshold n^(log_b a). Case 1 (w polynomially smaller): Theta(n^(log_b a)); case 2 (same order): Theta(n^(log_b a) log n); case 3 (polynomially larger and regular): Theta(w(n)). Full proof from the levels of the tree, extended version with floors and ceilings, a table of applications, and the misuse when no case applies (w = n log n).Master Theorem →); binary-search recurrence. The bound 22 per level is attained by n=2t−1n=2^t-1 (all odd).
  • Exact: T(n)=⌊log⁡2n⌋+ν(n)−1T(n)=\lfloor\log_2n\rfloor+\nu(n)-1, ν(n)\nu(n) = number of 11 bits.
    • Induction: base n=1n=1 gives 00.
    • Even: T(n2)+1T(\frac n2)+1, ⌊log⁡2n2⌋=⌊log⁡2n⌋−1\lfloor\log_2\frac n2\rfloor=\lfloor\log_2n\rfloor-1, ν(n2)=ν(n)\nu(\frac n2)=\nu(n).
    • Odd: T(n−12)+2T(\frac{n-1}2)+2, ν(n−12)=ν(n)−1\nu(\frac{n-1}2)=\nu(n)-1.
    • So ⌊log⁡2n⌋\lfloor\log_2n\rfloor squarings and ν(n)−1\nu(n)-1 multiplications by xx. Minimum kk (n=2kn=2^k), maximum 2k2k (n=2k+1−1n=2^{k+1}-1).
    • x13x^{13}: 13→6→3→113\to6\to3\to1, 2+1+2=52+1+2=5 operations (against 1212); x31x^{31}: 4+5−1=84+5-1=8.
  • Iterative: n=bk…b0n=b_k\dots b_0, xn=∘bi=1x2ix^n=\circ_{b_i=1}x^{2^i}, x2i=x2i−1∘x2i−1x^{2^i}=x^{2^{i-1}}\circ x^{2^{i-1}}.
    • POWER2: p←ep\leftarrow e, s←xs\leftarrow x; for i=0..ki=0..k: if bi=1b_i=1 then p←p∘sp\leftarrow p\circ s; then s←s∘ss\leftarrow s\circ s.
    • Literal cost k+1+ν(n)≤2(⌊log⁡2n⌋+1)k+1+\nu(n)\le2(\lfloor\log_2n\rfloor+1).
    • POWER3: bits via EVEN(m)(m) and m←⌊m2⌋m\leftarrow\lfloor\frac m2\rfloor, m=nm=n initially.
    • 13=1101213=1101_2: p=x,x,x5,x13p=x,x,x^5,x^{13}; s=x2,x4,x8,x16s=x^2,x^4,x^8,x^{16}.
    • The literal code does 22 more applications than POWER (e∘se\circ s at the first 11 bit and the last useless squaring); with p←sp\leftarrow s at the first 11 bit and no last squaring they coincide.
  • Fibonacci: M=(1110)M=\begin{pmatrix}1&1\\1&0\end{pmatrix}, Mn=(Fn+1FnFnFn−1)M^n=\begin{pmatrix}F_{n+1}&F_n\\F_n&F_{n-1}\end{pmatrix}, FnF_n with Θ(log⁡n)\Theta(\log n) 2×22\times2 products (M13M^{13} gives F13=233F_{13}=233) if scalars are unit cost.
  • Common mistakes: unit cost with growing operands; omitting the base case n=1n=1; counting log⁡2n\log_2n instead of ⌊log⁡2n⌋+1\lfloor\log_2n\rfloor+1 bits; thinking commutativity is needed (associativity suffices).

Teoria collegata