Skip to content

Commit b695175

Browse files
authored
binary exponentiation
1 parent 3ecb193 commit b695175

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

other/binary_exponentiation.java

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
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+
*/
8+
9+
/**
10+
* @author chinmoy159
11+
* @version 1.0 dated 10/08/2017
12+
*/
13+
public class bin_expo
14+
{
15+
/**
16+
* function :- b_expo (int a, int b)
17+
* returns a^b
18+
*/
19+
public static int b_expo(int a, int b)
20+
{
21+
/*
22+
* iterative solution
23+
*/
24+
int res;
25+
for (res = 1; b > 0; a *=a, b >>= 1) {
26+
if ((b&1) == 1) {
27+
res *= a;
28+
}
29+
}
30+
return res;
31+
/*
32+
* recursive solution
33+
if (b == 0) {
34+
return 1;
35+
}
36+
if (b == 1) {
37+
return a;
38+
}
39+
if ((b & 1) == 1) {
40+
return a * b_expo(a*a, b >> 1);
41+
} else {
42+
return b_expo (a*a, b >> 1);
43+
}
44+
*/
45+
}
46+
/**
47+
* function :- b_expo (long a, long b, long c)
48+
* return (a^b)%c
49+
*/
50+
public static long b_expo(long a, long b, long c)
51+
{
52+
/*
53+
* iterative solution
54+
*/
55+
long res;
56+
for (res = 1l; b > 0; a *=a, b >>= 1) {
57+
if ((b&1) == 1) {
58+
res = ((res%c) * (a%c)) % c;
59+
}
60+
}
61+
return res;
62+
/*
63+
* recursive solution
64+
if (b == 0) {
65+
return 1;
66+
}
67+
if (b == 1) {
68+
return a;
69+
}
70+
if ((b & 1) == 1) {
71+
return ((a%c) * (b_expo(a*a, b >> 1)%c))%c;
72+
} else {
73+
return b_expo (a*a, b >> 1)%c;
74+
}
75+
*/
76+
}
77+
}

0 commit comments

Comments
 (0)