Day 10 of 30 Ruby Coding Challenge: Recursive Factorial Numbers
Day 10 of 30 - We are going solve the Factorial calculation using recursion in Ruby and learn a Ruby way to solve this type of problem.
Join the DZone community and get the full member experience.
Join For FreeHey!
Today, we’re going to solve the previous Factorial problem using recursion in Ruby. This is the written version of the Youtube video :).
Just a reminder, it doesn’t matter if you’re using Ruby, Python, JavaScript, or your favorite language — what really matters is the concepts and logic used to solve problems.
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!
Real example:
xxxxxxxxxx
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:
xxxxxxxxxx
def factorial(number)
result = number
while number > 1
result = result * (number - 1)
number = number - 1
end
return result
end
puts factorial(5) # 120
Recursion
Again, just recalling what recursion 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:
xxxxxxxxxx
5! = 5*4*3*2*1
But you can actually calculate this way:
xxxxxxxxxx
5! = 5*4!
Because 4! = 432*1, which is a small part of the 5! problem
You can go further and say:
xxxxxxxxxx
5! = 5*4*3!
A little bit more
xxxxxxxxxx
5! = 5*4*3*2!
And finally
xxxxxxxxxx
5! = 5*4*3*2*1
Notice that we’ve broken that down into smaller Factorial calculations.
The recursive Ruby method will be like the following:
xxxxxxxxxx
def factorial(number)
return 1 if number == 0
return number * factorial(number - 1)
end
Notice that the function:
- Returns 1 if the number is equal to 0. That’s the criteria to stop the method execution.
- Returns number * factorial(number - 1) which, as we saw, is a method calling on itself.
A leaner version of this method in Ruby would be:
xxxxxxxxxx
def factorial(number)
number == 0 ? 1 : number * factorial(number - 1)
end
Also notice that:
- We don’t need to explicitly use return in Ruby.
- We’re using a ternary condition, which in our case makes the readability (in my opinion) much better.
That’s it!
Hope you liked it and see you tomorrow in the next challenge :).
Don’t forget to come by and say hi!
Published at DZone with permission of Alexandre Gama. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Seven Steps To Deploy Kedro Pipelines on Amazon EMR
-
Health Check Response Format for HTTP APIs
-
Microservices With Apache Camel and Quarkus (Part 2)
-
Authorization: Get It Done Right, Get It Done Early
Comments