Skip to content

Commit c2da1a3

Browse files
created power_of_n.py
1 parent 39a8411 commit c2da1a3

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+
#Python program to calculate x raised to the power n (i.e., x^n)
2+
3+
# Script Name : power_of_n.py
4+
# Author : Himanshu Gupta
5+
# Created : 2nd September 2023
6+
# Last Modified :
7+
# Version : 1.0
8+
# Modifications :
9+
# Description : Program which calculates x raised to the power of n, where x can be float number or integer and n can be positive or negative number
10+
# Example 1:
11+
12+
# Input: x = 2.00000, n = 10
13+
# Output: 1024.00000
14+
# Example 2:
15+
16+
# Input: x = 2.10000, n = 3
17+
# Output: 9.26100
18+
# Example 3:
19+
20+
# Input: x = 2.00000, n = -2
21+
# Output: 0.25000
22+
# Explanation: 2^-2 = 1/(2^2) = 1/4 = 0.25
23+
24+
#Class
25+
class Solution:
26+
27+
def binaryExponentiation(self, x: float, n: int) -> float:
28+
if n == 0:
29+
return 1
30+
31+
# Handle case where, n < 0.
32+
if n < 0:
33+
n = -1 * n
34+
x = 1.0 / x
35+
36+
# Perform Binary Exponentiation.
37+
result = 1
38+
while n != 0:
39+
# If 'n' is odd we multiply result with 'x' and reduce 'n' by '1'.
40+
if n % 2 == 1:
41+
result *= x
42+
n -= 1
43+
# We square 'x' and reduce 'n' by half, x^n => (x^2)^(n/2).
44+
x *= x
45+
n //= 2
46+
return result
47+
48+
49+
if __name__ == "main":
50+
obj = Solution() #Creating object of the class Solution
51+
52+
#Taking inouts from the user
53+
x = float(input("Enter the base number: "))
54+
n = int(input("Enter the power number: "))
55+
56+
#calling the function using object obj to calculate the power
57+
answer = obj.binaryExponentiation(x, n)
58+
print(answer) #answer

0 commit comments

Comments
 (0)