When I first learned about recursive functions, I had a hard time understanding them. I understood it by writing it on paper at that time, so I illustrated it this time.
A function that calls itself within the function defined by def ~ end
.
Fibonacci functions are often treated as an introduction to recursive functions if they are famous.
If you are new to this, please search.
The product of n consecutive natural numbers from> 1 to n is called the factorial of n. Write n !, for example, 4! = 1 × 2 × 3 × 4 = 24. However, the factorial of 0 is 1.
Source: goo dictionary
def factorial(num)
if num == 1 || num == 0
return 1
end
return num * factorial(num - 1)
end
num <0
is passed, it is not considered this time.It's a very simple code, but it's surprisingly confusing when you think about it in your brain.
I'm still new to recursive functions, so I'm still confused about complicated things. However, I think that the code illustrated this time is the basis, so if I get lost, I will return to the beginning.
I hope this article helps someone understand recursive functions.
Recommended Posts