CEO Underworld - 8 months ago 69

Ruby Question

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 Source

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