SharedL1-EX09.ipynbOpen in CoCalc
L1-EX09
import math

def npow(A, n, verbose=False):

    if n == 0:
        return 1

    if n == 1:
        return A

    e = math.floor(n / 2)

    m = npow(A, e)

    if (verbose):
        print("A:" + str(A))
        print("n:" + str(n))
        print("e:" + str(e))
        print("m:" + str(m))
        print("================")

    return m * m if n % 2 == 0 else m * m * A
npow(3,5,true)
A:3 n:5 e:2.0 m:9 ================
243
npow(2,4,true)
A:2 n:4 e:2.0 m:4 ================
16
npow(5,3,true)
A:5 n:3 e:1.0 m:5 ================
125