CEO Underworld CEO Underworld - 8 days ago 6
Ruby Question

How to exclude the floats from the factorial method in Ruby?

When finding factorial, using recursion(Ruby), following code finds the factorial of the whole numbers but fails in cases of floats. How can I tweak this?
I thought about using domains like in Maths but I do not know how to do that, yet.

def factorial num
if num < 0
return "Please provide a whole number."
end

if num <=1
1
else
num * factorial(num-1)
end

end

Answer

The easiest way to filter out floats is to use what makes them float :) They are not completely divisible by 1.

def factorial num
  if (num % 1 != 0 || num < 0)
    return "Please provide a whole number."
  end

  if num <=1
    1
  else
    num * factorial(num-1)
  end
end

Hope that helps. Cheers

Comments