-
Notifications
You must be signed in to change notification settings - Fork 19
/
8.5-Recursive_Multiply.py
60 lines (51 loc) · 1.49 KB
/
8.5-Recursive_Multiply.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
57
58
59
60
# CTCI 8.5
# Recursive Multiply
#-------------------------------------------------------------------------------
# My Solution O(logn)
#-------------------------------------------------------------------------------
def mult(n1, n2):
if n1 > n2:
a, b = n1, n2
else:
a, b = n2, n1
return helper(a, b, {})
def helper(big, small, memo):
if small == 0:
return 0
elif small == 1:
return big
elif small in memo:
return memo[small]
# Compute Half
s = small >> 1
side1 = helper(big, s, memo)
side2 = side1
# If an odd number
if small % 2 == 1:
# Actually do the computations out instead of just x2
side2 = helper(big, small-s, memo)
# sum and cache
memo[small] = side1 + side2
return memo[small]
#-------------------------------------------------------------------------------
# INEFFICIENT SOLUTION O(n)
#-------------------------------------------------------------------------------
def multiply(n1, n2):
if n1 == 0 or n2 == 0:
return 0
return help(n1, n2, 0)
def help(n1, n2, result):
if n2 == 0:
return result
if result == 0:
result = n1
else:
result += n1
n2 -= 1
return help(n1, n2, result)
#-------------------------------------------------------------------------------
#Testing
#-------------------------------------------------------------------------------
print (mult(9, 5))
print (mult(12, 12))
print (mult(9, 512321))