DEV Community

Cover image for Ruby Challenge: Calculating Factorials with Negative Numbers
Peter Kim Frank for CodeNewbie

Posted on with Erin A Olinick • Updated on

Ruby Challenge: Calculating Factorials with Negative Numbers

Welcome to Ruby Tuesday, a weekly post where we explore the world of Ruby programming language. Today's challenge is all about modifying a factorial method in Ruby to handle negative input numbers.


In this code, the factorial method takes a number n as input and recursively calculates its factorial. The base case is when n is 0, in which case the method returns 1. Otherwise, the method multiplies n by the factorial of n-1.

When we call factorial(5) using the puts method, it calculates the factorial of 5 (i.e., 5 * 4 * 3 * 2 * 1) and outputs the result, which is 120.

def factorial(n)
if n == 0
1
else
n * factorial(n-1)
end
end

puts factorial(5) # outputs 120
Enter fullscreen mode Exit fullscreen mode

Challenge:

Modify the factorial method to handle negative input numbers.

Put your Ruby skills to the test. Go!


Leave your solutions, thoughts, tricks, and questions in the comments below. And be sure to join us here on CodeNewbie Org next Ruby Tuesday for more exciting challenges and tips to enhance your Ruby skills!.

#codenewbie

The most supportive community of programmers and people learning to code.

Top comments (3)

Collapse
 
topofocus profile image
Hartmut B.

That's too easy ....

3.2.0 :021 > def factorial(n)
3.2.0 :022 > if n == 0
3.2.0 :023 > 1
3.2.0 :024 > else
3.2.0 :025 > n>0 ? n * factorial(n-1) : n * factorial(n+1)
3.2.0 :026 > end
3.2.0 :027 > end
Enter fullscreen mode Exit fullscreen mode

q&d off cause

Collapse
 
codeandclay profile image
Oliver • Edited

Great answer.

What answer should it give when the input is -5? I assume -120 is correct?

I've modified your answer to be more idiomatic.

class Integer
  def factorial
    return 1 if self.zero?

    return self * (self+1).factorial if self <= 0

    self * (self-1).factorial
  end
end
Enter fullscreen mode Exit fullscreen mode

By defining the method on Integer, I can now call 5.factorial or -5.factorial.

I can see there is room for re-factoring. Would it be clearer without the duplication?

5.factorial
# => 120
-5.factorial
# => -120
0.factorial
# => 1
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rachelfazio profile image
Rachel Fazio

Love this!