Created
January 28, 2018 07:14
-
-
Save jianminchen/9158a81b79fc3aa2a0dc9050e50d30e3 to your computer and use it in GitHub Desktop.
Power calculation using recursive solution - do not need memoization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Find the nth power of x | |
n >= 1 -- int | |
x >= 1 -- int | |
find: x**n | |
def pow(x, n): | |
# Base case | |
if (n == 1): | |
return x # x**1 = x | |
else: | |
half = n/2 | |
result = pow(x, half) | |
if (x is even): | |
return result * result | |
else: | |
# x is odd | |
return result * result * x | |
# result = pow(x, a) * pow(x, b) | |
# memo[n] = result | |
# return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment