File tree Expand file tree Collapse file tree 1 file changed +30
-11
lines changed
src/chapter18divideandconquer Expand file tree Collapse file tree 1 file changed +30
-11
lines changed Original file line number Diff line number Diff line change 8
8
# warranty; without even the implied warranty of
9
9
# merchantability or fitness for a particular purpose.
10
10
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
+
16
21
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
+
You can’t perform that action at this time.
0 commit comments