I tried to build a simple code that solved square operational with value n using python, plus, i want to learn recursion. I made three different style code like below syntax:
First code
def pangkat(nilai, pangkat):
a = int(1)
for i in range(pangkat):
a = a * nilai
return a
if __name__ == "__main__":
print(pangkat(13, 8181))
Second Code
def pangkat(nilai, pangkat):
hasil = nilai**pangkat
return hasil
if __name__ == "__main__":
print(pangkat(13, 8181))
Third Code
def pangkat(nilai, pangkatnilai):
if pangkatnilai == 1:
return nilai
return nilai * pangkat(nilai, pangkatnilai-1)
if __name__ == "__main__":
print(pangkat(13,8181))
Note : param nilai as number that will be raised, and pangkat as number that will raised param nilai), all of these code works well for example, when i fill the nilai and param
Input 0
pangkat(13, 12)
Output 0
23298085122481
The problem occurred when i changed the param pangkat >= 1000, it will said , it will gave me an error but only in third code.
Traceback (most recent call last):
File "pang3.py", line 8, in <module>
print(pangkat(13,1000))
File "pang3.py", line 5, in pangkat
return nilai * pangkat(nilai, pangkatnilai-1)
File "pang3.py", line 5, in pangkat
return nilai * pangkat(nilai, pangkatnilai-1)
File "pang3.py", line 5, in pangkat
return nilai * pangkat(nilai, pangkatnilai-1)
[Previous line repeated 995 more times]
File "pang3.py", line 2, in pangkat
if pangkatnilai == 1:
RecursionError: maximum recursion depth exceeded in comparison
While the first and second code works well. What could go wrong with my recursion function ? plus i need the explanation for it, Thanks!
NB : As possible, is there any better approach for using recursion like i needed ? i build my recursion using my own logic, so i expect if someone had better approach for that code.