Skip to content

Commit 56513cb

Browse files
junthbasnetpoyea
authored andcommitted
add-binary-exponentiation (#790)
1 parent 30a3582 commit 56513cb

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

maths/BinaryExponentiation.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#Author : Junth Basnet
2+
#Time Complexity : O(logn)
3+
4+
def binary_exponentiation(a, n):
5+
6+
if (n == 0):
7+
return 1
8+
9+
elif (n % 2 == 1):
10+
return binary_exponentiation(a, n - 1) * a
11+
12+
else:
13+
b = binary_exponentiation(a, n / 2)
14+
return b * b
15+
16+
17+
try:
18+
base = int(input('Enter Base : '))
19+
power = int(input("Enter Power : "))
20+
except ValueError:
21+
print ("Invalid literal for integer")
22+
23+
result = binary_exponentiation(base, power)
24+
print("{}^({}) : {}".format(base, power, result))
25+

0 commit comments

Comments
 (0)