Programming Questions

  • Newest
  • Popular Tags
  • Ask Question
  • Factorial in Ruby
    I am trying to do the factorial in ruby. My code is below but it's not working.
    def FirstFactorial(num)
      return num 
    erickeno posted this question on 5/15/14 | factorial, ruby
  • +
  • 4
  • -
  • By doing this you're not changing the value inside "num" When you use this kind of methods be aware that they do not affect your variable directly but instead returns a value that you can store/return You have two solutions :
     return num.downto(1).reduce(:*) 
    num = num.downto(1).reduce(:*)
    return num
  • +
  • 3
  • -
  • The solution from ziroshell will fail when supplied with 0.
    irb(main):007:0> fact(0)
    => nil
    0! is mathematically defined as 1 so you need an edge case to handle the situation where there is nothing to reduce. Adding a failsafe that returns one when the reduce fails takes care of this.
    num.downto(1).reduce(:*)  || 1
    Log in to write an answer.