forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_exponentiation_3.py
170 lines (118 loc) · 2.5 KB
/
binary_exponentiation_3.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
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
"""
* Binary Exponentiation for Powers
* This is a method to find a^b in a time complexity of O(log b)
* This is one of the most commonly used methods of finding powers.
* Also useful in cases where solution to (a^b)%c is required,
* where a,b,c can be numbers over the computers calculation limits.
* Done using iteration, can also be done using recursion
* @author chinmoy159
* @version 1.0 dated 10/08/2017
"""
def b_expo(a: int, b: int) -> int:
"""
>>> b_expo(1, 1)
1
>>> b_expo(2, 1)
2
>>> b_expo(3, 1)
3
>>> b_expo(4, 1)
4
>>> b_expo(1, 2)
1
>>> b_expo(2, 2)
4
>>> b_expo(3, 2)
9
>>> b_expo(4, 2)
16
>>> b_expo(1, 3)
1
>>> b_expo(2, 3)
8
>>> b_expo(3, 3)
27
>>> b_expo(4, 3)
64
"""
res = 1
while b > 0:
if b & 1:
res *= a
a *= a
b >>= 1
return res
def b_expo_mod(a: int, b: int, c: int) -> int:
"""
>>> b_expo_mod(1, 1, 7)
1
>>> b_expo_mod(2, 1, 7)
2
>>> b_expo_mod(3, 1, 7)
3
>>> b_expo_mod(4, 1, 7)
4
>>> b_expo_mod(1, 2, 7)
1
>>> b_expo_mod(2, 2, 7)
4
>>> b_expo_mod(3, 2, 7)
2
>>> b_expo_mod(4, 2, 7)
2
>>> b_expo_mod(1, 3, 7)
1
>>> b_expo_mod(2, 3, 7)
1
>>> b_expo_mod(3, 3, 7)
6
>>> b_expo_mod(4, 3, 7)
1
>>> b_expo_mod(1, 1, 5)
1
>>> b_expo_mod(2, 1, 5)
2
>>> b_expo_mod(3, 1, 5)
3
>>> b_expo_mod(4, 1, 5)
4
>>> b_expo_mod(1, 2, 5)
1
>>> b_expo_mod(2, 2, 5)
4
>>> b_expo_mod(3, 2, 5)
4
>>> b_expo_mod(4, 2, 5)
1
>>> b_expo_mod(1, 3, 5)
1
>>> b_expo_mod(2, 3, 5)
3
>>> b_expo_mod(3, 3, 5)
2
>>> b_expo_mod(4, 3, 5)
4
"""
res = 1
while b > 0:
if b & 1:
res = ((res % c) * (a % c)) % c
a *= a
b >>= 1
return res
"""
* Wondering how this method works !
* It's pretty simple.
* Let's say you need to calculate a ^ b
* RULE 1 : a ^ b = (a*a) ^ (b/2) ---- example : 4 ^ 4 = (4*4) ^ (4/2) = 16 ^ 2
* RULE 2 : IF b is ODD, then ---- a ^ b = a * (a ^ (b - 1)) :: where (b - 1) is even.
* Once b is even, repeat the process to get a ^ b
* Repeat the process till b = 1 OR b = 0, because a^1 = a AND a^0 = 1
*
* As far as the modulo is concerned,
* the fact : (a*b) % c = ((a%c) * (b%c)) % c
* Now apply RULE 1 OR 2 whichever is required.
"""
if __name__ == "__main__":
import doctest
doctest.testmod()