[英]exponential multiplication algorithm that runs in O(n) time?
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. 假设我们想要计算值x ^ y,其中x和y分别是具有m和n位的正整数。 One way to solve the problem is to perform y - 1 multiplications by x. 解决问题的一种方法是用x进行y-1次乘法。 Can you give a more efficient algorithm that uses only O(n) multiplication steps? 你能提供一个只使用O(n)乘法步骤的更有效的算法吗?
Would this be a divide and conquer algorithm? 这会是一个分而治之的算法吗? y-1 multiplications by x would run in theta(n) right? y-1乘以x将在θ(n)右边运行? .. I don't know where to start with this question ..我不知道从哪里开始这个问题
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)) 你可以计算所有2的幂的x ^ z: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). 简单地从1到n并且应用x ^(2 ^(i + 1))= x ^(2 ^ i)* x ^(2 ^ i)。
Now you can use these n values to compute x^y: 现在您可以使用这些n值来计算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) 一切都在O(n)完成
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);
The y-1
multiplications solution is based on the identity x^y = x * x^(y-1)
. y-1
乘法解决方案基于身份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. 通过重复应用身份,您知道您将以y-1
步骤将y
减少到1
。
A better idea is to decrease y more "energically". 更好的想法是更“减少”地减少y。 Assuming an even y
, we have x^y = x^(2*y/2) = (x^2)^(y/2)
. 假设偶数y
,我们得到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)
. 假设奇数y
,我们得到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
. 如果继续使用x^2
而不是x
进行功率计算,您会看到可以将y
减半。
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
读作加权位的总和。 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. 您可以通过平方获得所需的x幂,并且y的二进制分解告诉您要乘以哪些幂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.