0
#This function should return n!
def factorial(n)
  return nil if n < 0
  n == 0 ? 1 : n*factorial(n-1)
end

Just starting out and this function is blowing my mind I would write this function like this:

def factorial(n)
  result = 1

  if n == 0 
    return 1
  end

  while n > 0
    result *= n
    n -= 1
  end
  return result
end

I understande the short hand for the if/else statement. What I dont understand is using n*factorial(n-1) inside the function itself.

It looks like the factorial function is called inside the factorial function, but that can't be whats going on right?

4
  • 1
    That is in fact what is going on here. This is a recursive approach to computing factorials. Commented Feb 20, 2015 at 22:11
  • that is exactly whats going on. the factorial function is being called inside itself. Commented Feb 20, 2015 at 22:12
  • "To understand recursion, you must first understand recursion." Commented Feb 20, 2015 at 22:17
  • Thanks guys just the answer I was looking for. Now that I know what its called i'll be sure to look into recursion further. Commented Feb 20, 2015 at 22:24

1 Answer 1

2

Factorial(5) evaluates to

5 * factorial(4)

factorial(4) evaluates to

4 * factorial(3)

factorial(3) evaluates to

3 * factorial(2)

factorial(2) evaluates to

2 * factorial(1)

factorial(1) evaluates to 1 because 1 <= 1

Substituting values appropriately results in

5 * factorial(4)
5 * 4 * factorial(3)
5 * 4 * 3 * factorial(2)
5 * 4 * 3 * 2 * factorial(1)
5 * 4 * 3 * 2 * 1

It's called recursion, the method is calling itself each time it evaluates until it meets the base case of 1 which is what this statement is doing: n == 0 ? 1 : n*factorial(n-1) :)

Sign up to request clarification or add additional context in comments.

2 Comments

Clear and to the point, Thanks!
@RaSedg - Would appreciate if you mark it as the answer if you have a moment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.