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?

RaSedg
  • 111
  • 1
  • 10

1 Answers1

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) :)

hummmingbear
  • 2,294
  • 5
  • 25
  • 42