Skip to content

Commit 49aba6b

Browse files
authored
Update ExponentialWithDivideAndConquer.py
1 parent 2c65531 commit 49aba6b

File tree

1 file changed

+30
-11
lines changed

1 file changed

+30
-11
lines changed

src/chapter18divideandconquer/ExponentialWithDivideAndConquer.py

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,34 @@
88
# warranty; without even the implied warranty of
99
# merchantability or fitness for a particular purpose.
1010

11-
def power(k, n):
12-
if n == 0: return 1
13-
x = power(k, math.floor(n / 2))
14-
if n % 2 == 0: return pow(x, 2)
15-
else: return k * pow(x, 2)
11+
import math
12+
def power_brute_force(k, n):
13+
"""linear power algorithm"""
14+
x = k
15+
for i in range(1, n):
16+
x *= k
17+
return x
18+
19+
print power_brute_force(2, 3)
20+
1621

17-
def powerBruteForce(k, n):
18-
"""linear power algorithm"""
19-
x = k;
20-
for i in range(1, n):
21-
x *= k
22-
return x
22+
23+
def power_divide_and_conquer(k, n):
24+
"""Divide and Conquer power algorithm"""
25+
26+
# base case
27+
if n == 0:
28+
return 1
29+
30+
# base case
31+
if k == 0:
32+
return 0
33+
34+
x = power_divide_and_conquer(a, math.floor(n/2))
35+
if n % 2 == 0:
36+
return x * x
37+
else:
38+
return k * x * x
39+
40+
print power_divide_and_conquer(2, 4)
41+

0 commit comments

Comments
 (0)