0

I came across the following code snippet for fast exponentiation. I can see that it works correctly, but I do not understand the logic that the author used to code it up so concisely. I do know the fast exponentiation concept and the general code one finds for it that uses divide and conquer recursively. Although the code snippet below must be doing exactly that, I am not able to wrap my head around what logic the author used to code it.

Could someone please explain?

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;
}
user3760100
  • 679
  • 1
  • 9
  • 20

1 Answers1

0

For example, 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

Hope this answers your question!