Main idea behind this is

B^{e}=B if e = 1

B^{e}=B*B^{e-1} if e is odd

B^{e}=X^{2} where X = B^{e/2} if e is even

Here’s the python code for the same.

#calculating x^n def logNexp(x,n): #base conditions if n == 0: return 1 if n == 1: return x #holding x in case n is odd temp = x x = logNexp(x,n>>1) x = x*x #if n is odd if (n&1): x = temp*x return x

you can try other variations also, check this at wiki

Advertisements