File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments