Skip to content

Commit c39f379

Browse files
Utsav1999cclauss
authored andcommitted
Added Finding Exponent Program (TheAlgorithms#2238)
* Finding Exponent Program * Build Error Fix - 1 * Build Error Fix - 2 * Error Fix - 1 datatype * self-documenting naming convension added * Update and rename exponent_recursion.py to power_using_recursion.py * Fix typo * Fix typo Co-authored-by: Christian Clauss <[email protected]>
1 parent 05cfc25 commit c39f379

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

Diff for: maths/power_using_recursion.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""
2+
== Raise base to the power of exponent using recursion ==
3+
Input -->
4+
Enter the base: 3
5+
Enter the exponent: 4
6+
Output -->
7+
3 to the power of 4 is 81
8+
Input -->
9+
Enter the base: 2
10+
Enter the exponent: 0
11+
Output -->
12+
2 to the power of 0 is 1
13+
"""
14+
15+
16+
def power(base: int, exponent: int) -> float:
17+
"""
18+
power(3, 4)
19+
81
20+
>>> power(2, 0)
21+
1
22+
>>> all(power(base, exponent) == pow(base, exponent)
23+
... for base in range(-10, 10) for exponent in range(10))
24+
True
25+
"""
26+
return base * power(base, (exponent - 1)) if exponent else 1
27+
28+
29+
if __name__ == "__main__":
30+
print("Raise base to the power of exponent using recursion...")
31+
base = int(input("Enter the base: ").strip())
32+
exponent = int(input("Enter the exponent: ").strip())
33+
result = power(base, abs(exponent))
34+
if exponent < 0: # power() does not properly deal w/ negative exponents
35+
result = 1 / result
36+
print(f"{base} to the power of {exponent} is {result}")

0 commit comments

Comments
 (0)