Today we’re going to solve the previous Factorial problem using recursion in Ruby 👌. This is the post version of the Youtube video :)
If you haven’t watched the previous video, I just want to remember the definition of a Factorial number
A Factorial number N is the product of all positive integers less than or equal to the number N
We indicate a Factorial number as N!
5! = 5*4*3*2*1 # result in 120
A possible (and not so beautiful) solution to this problem is the solution in the first video:
def factorial(number) result = number while number > 1 result = result * (number - 1) number = number - 1 end return result end puts factorial(5) # 120
Again, just recalling what the recursion technique is:
Recursion is when you solve a problem by breaking the problem down into smaller versions of the same problem
And when it comes to coding, the method or function calls on itself :)
Before going to code, let’s see the first example:
5! = 5*4*3*2*1
But you can actually calculate this way:
5! = 5*4!
Because 4! = 432*1, which is a small part of the 5! problem
You can go further and say:
5! = 5*4*3!
A little bit more
5! = 5*4*3*2!
5! = 5*4*3*2*1
Notice that we’ve broken that down into smaller Factorial calculations
The recursive Ruby method will be the following:
def factorial(number) return 1 if number == 0 return number * factorial(number - 1) end
A more leaner version of this method in Ruby would be:
def factorial(number) number == 0 ? 1 : number * factorial(number - 1) end
Also notice that:
Hope you liked it and see you tomorrow in the next challenge :)
Don’t forget to keep in touch and say hi Alex
You’ll receive coding courses, tutorials and personal posts! I’ll be happy to send them to you, weekly :)