We will use representation change to design and efficient exponentiation
First consider evaluating a polynomial, p(x) = anxn +
an-1xn-1 + ... + a1x + a0
If we calculate powers of x by successive multiplication then the total number of multiplications to evaluate the polynomial is
M(n) = ∑i=1n i ε Θ(n2)
This an excess of multiplications.
Horner's rule uccessively uses the previous power calculation to calculate the next power.
p(x) = (...(( anx + an-1 )x + an-1)x... ) + a0
There are n multiplications. (count the parenthesis)
Consider the problem of calculating an. A direct application has cost n and so does not improve the brute force cost.
Represent the power, n, in binary digits,
n = bI ... bi ... b0
then
n = p(x=2)
= bIxI
+ ... + bixi
+ ... + b0
= bI2I + ... + bi2i + ... + b0
So we can use this determine the power of a
an = ap(2) = a bI2I + ... + bi2i + ... + b0
Note a 2p+bi2i = a2p•abi = (ap)2•abi
= (ap)2 if bi=0
or
= (ap)2•a if bi =1
Algorithm LeftRightBinaryExponent(a, n = b[0...I])
product ← a
for i ← I-1 downto 0 do
product**
if b[i] = 1 then product ← product*a
return product
There is also a right to left binary exponentiation
Algorithm RightLeftBinaryExponent(a, n = b[0...I))
term ← a
if b[0]=1 then product ← a
else product ← 1
for i ← 1 to I do
term**
if b[i] = 1 then product ← product*term
return product
The number of multiplications is
(I-1) ≤ M(n) ≤ 2(I-1)
so the cost is ε Θ(I) = Θ(lg n)
The joke about how a math professor makes tea by putting the pot on the shelf.
1. Least common multiple of two intergers is the smallest integer divisible by m and n
lcm(m, n) = m•n/gcd(m, n)
2. Counting paths between two vertices in a graph represented by adjacency matrix, A, can be calculated by powers of A. Not that Ak[i, j] is the number of paths between vi and vj with length k. Note that binary exponentiation can be used for matrices. To determine if the any path between vertices, we need to check An. If non zero than there is a path.
3. Find the minimum can be reduce to finding the maximum using
min f(x) = - max(-f(x))
4. The continuous knapsack problem can be reduced to linear programming problem
maximize f(x) = ∑j vjxj
subject to ∑j wjxj ≤ W
0 ≤ xj ≤ 1 for j = 1, ... , n
4. Many problems can be reduce to a graph problem, the text demonstrate the river crossing problem as a graph.