Understanding Factorial Code

Perhaps the answer to my question will end up being: “Both are valid lines of code.”

… but I’ve been starting out and its been a little difficult thinking through my own problems without looking at the solution.

The task is part of the loops exercises in Ruby and I need to find the factorial. As I learned factorials counting down (ie - 3! = 321) I started thinking using the “-=” operation. After giving it some thinking I came up with:

def factorial(num)
product = 1

  • while num > 0*
  • product = num
  • num-=1*
  • end*
  • return product*
    end

puts factorial(3) # => 6, because 1 * 2 * 3 = 6
puts factorial(5) # => 120, because 1 * 2 * 3 * 4 * 5 = 120

After having it produce the correct results, I excitedly turned to the solutions page to see that it was not the same:

def factorial(num)

  • product = 1*

  • i = 2*

  • while i <= num*

  • product = i

  • i += 1*

  • end*

  • return product*
    end


Is there a reason why they used i+=1 instead of counting down like I did? Is it to avoid a common error that I might get in the future?