-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path61_Google_Integer_Exponentiation.py
executable file
·56 lines (40 loc) · 1.59 KB
/
61_Google_Integer_Exponentiation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
"""
This problem was asked by Google.
Implement integer exponentiation.
That is, implement the pow(x, y) function, where x and y are integers and returns x^y.
Do this faster than the naive method of repeated multiplication.
For example, pow(2, 10) should return 1024.
"""
memo_table = {} # dictionary for memoization
def helper(number, exponent):
# if we've already calculated this exponent then just return that
if (number, exponent) in memo_table:
return memo_table[(number, exponent)]
if exponent == 1:
memo_table[(number, exponent)] = number
return memo_table[number, exponent]
if exponent == 0:
memo_table[(number, exponent)] = 1
return memo_table[(number, exponent)]
if exponent == 2:
# just a square of the number
memo_table[(number, exponent)] = number*number
return memo_table[(number, exponent)]
if exponent % 2 == 0:
# divisible by 2 so can be separated into equal sized groups
memo_table[(number, exponent)] = pow(number, exponent//2) * pow(number, exponent//2)
return memo_table[(number, exponent)]
else:
# can't be equally divided into groups
memo_table[(number, exponent)] = pow(number, exponent//2) * pow(number, exponent//2) * number
return memo_table[(number, exponent)]
def pow(number, exponent):
abs_exponent = abs(exponent)
result = helper(number, abs_exponent)
return 1/result if exponent<0 else result
if __name__ == '__main__':
print(pow(2, 10))
print(pow(3, 20))
print(pow(15, 15))
print(pow(15,0))
print(pow(2,-3))