Skip to content

Commit f09c995

Browse files
Merge pull request #1976 from HimanshuGupta-p1/master
Created power_of_n.py and made relevant changes
2 parents 39a8411 + a5e0616 commit f09c995

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

power_of_n.py

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Assign values to author and version.
2+
__author__ = "Himanshu Gupta"
3+
__version__ = "1.0.0"
4+
__date__ = "2023-09-03"
5+
6+
def binaryExponentiation(x: float, n: int) -> float:
7+
"""
8+
Function to calculate x raised to the power n (i.e., x^n) where x is a float number and n is an integer and it will return float value
9+
10+
Example 1:
11+
12+
Input: x = 2.00000, n = 10
13+
Output: 1024.0
14+
Example 2:
15+
16+
Input: x = 2.10000, n = 3
17+
Output: 9.261000000000001
18+
19+
Example 3:
20+
21+
Input: x = 2.00000, n = -2
22+
Output: 0.25
23+
Explanation: 2^-2 = 1/(2^2) = 1/4 = 0.25
24+
"""
25+
26+
if n == 0:
27+
return 1
28+
29+
# Handle case where, n < 0.
30+
if n < 0:
31+
n = -1 * n
32+
x = 1.0 / x
33+
34+
# Perform Binary Exponentiation.
35+
result = 1
36+
while n != 0:
37+
# If 'n' is odd we multiply result with 'x' and reduce 'n' by '1'.
38+
if n % 2 == 1:
39+
result *= x
40+
n -= 1
41+
# We square 'x' and reduce 'n' by half, x^n => (x^2)^(n/2).
42+
x *= x
43+
n //= 2
44+
return result
45+
46+
47+
if __name__ == "__main__":
48+
print(f"Author: {__author__}")
49+
print(f"Version: {__version__}")
50+
print(f"Function Documentation: {binaryExponentiation.__doc__}")
51+
print(f"Date: {__date__}")
52+
53+
print() # Blank Line
54+
55+
print(binaryExponentiation(2.00000, 10))
56+
print(binaryExponentiation(2.10000, 3))
57+
print(binaryExponentiation(2.00000, -2))
58+

0 commit comments

Comments
 (0)