Without using bit shifts, is there a way to compute 2 ^ n in O (n) time?
I was considering a solution using memoization, as I will always calculate first from n. i.e
d = dict()
def pwr2(n):
if n == 0:
return 1
if n == 1:
return 2
if n in d:
return d[n]
d[n] = 2 * pwr2(n-1)
return d[n]
But I'm not quite sure what the difficulty will be.
EDIT: I have to add that I use this part of the algorithm to convert binary to decimal faster than O (n ^ 2). As part of my separation and dormant algorithm, I have to multiply, increasing powers by two, so I tried using memoizing.
EDIT2: just submit my complete algorithm here to help eliminate the confusion pwr2dict = dict ()
def karatsuba(x, y):
// use karatsuba algorithm to multiply x*y
def pwr2(n):
if n == 0:
return 1
if n == 1:
return 2
if n in pwr2dict:
return pwr2dict[n]
pwr2dict[n] = karatsuba(pwr2(n-1),2)
return pwr2dict[n]
def binToDec(b):
if len(b) == 1:
return int(b)
n = int(math.floor(len(b)/2))
top = binToDec(b[:n])
bottom = binToDec(b[n:])
return bottom + karatsuba(top, pwr2(len(b)-n))
print binToDec("10110") // Prints 22
source
share