Reputation: 199
I am reading an algorithms textbook and I am stumped by this question:
Suppose we want to compute the value x^y, where x and y are positive integers with m and n bits, respectively. One way to solve the problem is to perform y - 1 multiplications by x. Can you give a more efficient algorithm that uses only O(n) multiplication steps?
Would this be a divide and conquer algorithm? y-1 multiplications by x would run in theta(n) right? .. I don't know where to start with this question
Upvotes: 3
Views: 214
Reputation:
The y-1
multiplications solution is based on the identity x^y = x * x^(y-1)
. By repeated application of the identity, you know that you will decrease y
down to 1
in y-1
steps.
A better idea is to decrease y more "energically". Assuming an even y
, we have x^y = x^(2*y/2) = (x^2)^(y/2)
. Assuming an odd y
, we have x^y = x^(2*y/2+1) = x * (x^2)^(y/2)
.
You see that you can halve y
, provided you continue the power computation with x^2
instead of x
.
Recursively:
Power(x, y)=
1 if y = 0
x if y = 1
Power(x * x, y / 2) if y even
x * Power(x * x, y / 2) if y odd
Another way to view it is to read y
as a sum of weighted bits. y = b0 + 2.b1 + 4.b2 + 8.b3...
The properties of exponentiation imply:
x^y = x^b0 . x^(2.b1) . x^(4.b2) . x^(8.b2)...
= x^b0 . (x^2)^b1 . (x^4)^b2 . (x^8)^b3...
You can obtain the desired powers of x by squaring, and the binary decomposition of y tells you which powers to multiply.
Upvotes: 0
Reputation: 1368
I understand this better in an iterative way:
You can compute x^z for all powers of two: z = (2^0, 2^1, 2^2, ... ,2^(n-1))
Simply by going from 1 to n and applying x^(2^(i+1)) = x^(2^i) * x^(2^i).
Now you can use these n values to compute x^y:
result = 1
for i=0 to n-1:
if the i'th bit in y is on:
result *= x^(2^i)
return result
All is done in O(n)
Upvotes: 2
Reputation:
Apply a simple recursion for divide and conquer. Here i am posting a more like a pseudo code.
x^y :=
base case: if y==1 return x;
if y%2==0:
then (x^2)^(y/2;
else
x.(x^2)^((y-1)/2);
Upvotes: 1