[Illustration] Factorial recursive function [Ruby]

Introduction

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.

What is a recursive function?

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.

What is factorial?

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

Code using recursive functions

def factorial(num)
  if num == 1 || num == 0
    return 1
  end
  return num * factorial(num - 1)
end

It's a very simple code, but it's surprisingly confusing when you think about it in your brain.

Illustrated

スクリーンショット 2020-10-16 22.45.16.png

At the end

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

[Illustration] Factorial recursive function [Ruby]
Ruby study memo (recursive function)
[Illustration] Finding the sum of coins with a recursive function [Ruby]
Ruby: Account editing function
[Ruby on Rails] Introduced paging function
Fibonacci sequence with (memoization) recursive function
[Ruby on Rails] CSV output function
[Ruby on Rails] Comment function implementation
[Ruby on Rails] DM, chat function