无法理解这个快速取幂代码中采用的方法?

时间:2017-03-18 14:00:08

标签: divide-and-conquer exponentiation

我遇到了以下用于快速取幂的代码段。我可以看到它正常工作,但我不明白作者用来编写它的逻辑如此简洁。我确实知道快速取幂概念和用于递归地使用分而治之的通用代码。虽然下面的代码片段必须完全正确,但我无法理解作者用来编码它的逻辑。

有人可以解释一下吗?

int fastExp(int base, int exponent ) {
   int b = 1, a = base;
   while(exponent > 0) {
       if(exponent%2) {
           b = b * a;
       }
       exponent /= 2;
       a = a * a;
   }
   return b;
}

1 个答案:

答案 0 :(得分:0)

例如,2 ^ 10

FIRST RUN
a = base
a = 2

if (exp(10) % 0)
do nothing

exponent /= 2
exponent = 10/2
exponent = 5

a = a * a
a = 2 * 2
a = 4

since exponent > 0, do another run
SECOND RUN
a = 4

if(exp(5) % 1)
b = b * a
b = 1 * 4
b = 4

exponent /= 2
exponent = 5/2
exponent = 2

a = a * a
a = 4 * 4
a = 16

since exponent > 0, do another run
THIRD RUN

a = 16

if(exp(2) % 2)
b = 4
do nothing here

exponent /= 2
exponent  = 2/2
exponent  = 1

a = 16 * 16
a = 256

since exponent > 0, do another run
FOURTH RUN

a = 256 

if(exp(1) % 2)
b = b * a
b = 4 * 256
b = 1024

exponent =/ 2
exponent = 1/2
exponent = 0

a = a * a
a = 254 * 254

b = 1024
since exponent is now 0,

return b

希望这能回答你的问题!