Skip to content

Commit a36ca7c

Browse files
authored
Create binary_exponentiation.py
1 parent 677dfe9 commit a36ca7c

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

other/binary_exponentiation.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
"""
2+
* Binary Exponentiation
3+
* This is a method to find a^b in a time complexity of O(log b)
4+
* This is one of the most commonly used methods of finding powers.
5+
* Also useful in cases where solution to (a^b)%c is required,
6+
* where a,b,c can be numbers over the computers calculation limits.
7+
* Done using iteration, can also be done using recursion
8+
9+
* @author chinmoy159
10+
* @version 1.0 dated 10/08/2017
11+
"""
12+
13+
14+
def b_expo(a, b):
15+
res = 1
16+
while b > 0:
17+
if b&1:
18+
res *= a
19+
20+
a *= a
21+
b >>= 1
22+
23+
return res
24+
25+
26+
def b_expo(a, b, c):
27+
res = 1
28+
while b > 0:
29+
if b&1:
30+
res = ((res%c) * (a%c)) % c
31+
32+
a *= a
33+
b >>= 1
34+
35+
return res
36+
37+
"""
38+
* Wondering how this method works !
39+
* It's pretty simple.
40+
* Let's say you need to calculate a ^ b
41+
* RULE 1 : a ^ b = (a*a) ^ (b/2) ---- example : 4 ^ 4 = (4*4) ^ (4/2) = 16 ^ 2
42+
* RULE 2 : IF b is ODD, then ---- a ^ b = a * (a ^ (b - 1)) :: where (b - 1) is even.
43+
* Once b is even, repeat the process to get a ^ b
44+
* Repeat the process till b = 1 OR b = 0, because a^1 = a AND a^0 = 1
45+
*
46+
* As far as the modulo is concerned,
47+
* the fact : (a*b) % c = ((a%c) * (b%c)) % c
48+
* Now apply RULE 1 OR 2 whichever is required.
49+
"""

0 commit comments

Comments
 (0)