forked from MTrajK/coding-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpower.py
More file actions
90 lines (66 loc) · 1.27 KB
/
power.py
File metadata and controls
90 lines (66 loc) · 1.27 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
'''
Power
Implement pow (a^b , a**b) method
=========================================
Using divide and conquer approach.
Time Complexity: O(LogB)
Space Complexity: O(LogB) , because of recursion calls stack
'''
############
# Solution #
############
def power(a, b):
if b < 0:
# negative power
return 1 / power_recursive(a, -b)
return power_recursive(a, b)
def power_recursive(a, b):
if b == 0:
return 1
res = power_recursive(a, b // 2)
res *= res
if b % 2 == 1:
res *= a
return res
###########
# Testing #
###########
# Test 1
# Correct result => 1
print(power(2, 0))
# Test 2
# Correct result => 2
print(power(2, 1))
# Test 3
# Correct result => 4
print(power(2, 2))
# Test 4
# Correct result => 8
print(power(2, 3))
# Test 5
# Correct result => 16
print(power(2, 4))
# Test 6
# Correct result => 32
print(power(2, 5))
# Test 7
# Correct result => 1024
print(power(2, 10))
# Test 8
# Correct result => 0.5
print(power(2, -1))
# Test 9
# Correct result => 0.25
print(power(2, -2))
# Test 10
# Correct result => 0.125
print(power(2, -3))
# Test 11
# Correct result => 0.0625
print(power(2, -4))
# Test 12
# Correct result => -8
print(power(-2, 3))
# Test 13
# Correct result => 16
print(power(-2, 4))