factorial(0) = 1, otherwise factorial(n) = n * factorial(n - 1). The smallest example of recursion with a single base case.

Algorithm

Canonical input n = 5 descends through six call frames and unwinds through five multiplications. Final result 120.

Basic Implementation

basic.rb
def factorial(n)
	if n == 0
		return 1
	end
	n * factorial(n - 1)
end

result = factorial(5)
puts result

Complexity

  • Time: O(n)
  • Space: O(n) call stack

Implementation notes

  • Ruby: same recursive shape as the other languages, with def factorial(n) documenting the integer contract by convention (Ruby is duck-typed; the lesson contract relies on caller hygiene).
  • The replay treats the call stack as a vertical list of frames; descent pushes, unwind pops with the computed multiplication shown.
base case `if n == 0 then return 1 end`
recursive call `n * factorial(n - 1)`