Skip to content

Commit f5917f5

Browse files
authored
Binary Exponentiation for Multiplication
1 parent f4c6578 commit f5917f5

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

other/binary_exponentiation_2.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""
2+
* Binary Exponentiation with Multiplication
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 result of multiplication.
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 = 0
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_mod(a, b, c):
27+
res = 0
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+
"""
39+
* Wondering how this method works !
40+
* It's pretty simple.
41+
* Let's say you need to calculate a ^ b
42+
* RULE 1 : a * b = (a+a) * (b/2) ---- example : 4 * 4 = (4+4) * (4/2) = 8 * 2
43+
* RULE 2 : IF b is ODD, then ---- a * b = a + (a * (b - 1)) :: where (b - 1) is even.
44+
* Once b is even, repeat the process to get a * b
45+
* Repeat the process till b = 1 OR b = 0, because a*1 = a AND a*0 = 0
46+
*
47+
* As far as the modulo is concerned,
48+
* the fact : (a+b) % c = ((a%c) + (b%c)) % c
49+
* Now apply RULE 1 OR 2, whichever is required.
50+
"""

0 commit comments

Comments
 (0)