The Canonical Starting Point: Factorials

Almost every textbook and lecture that teaches recursion starts with factorials. That really is a fine way to introduce the technique, so we won't buck tradition today.

The factorial of a positive integer is calculated by multiplying it by all positive integers smaller than itself. (Factorials are undefined for negative numbers, and the factorial of 0 is defined to be 1.) Standard mathematical notation for the factorial of a number n is n!, so we say, 5! = 1 × 2 × 3 × 4 × 5 = 120.

Factorials are often used for problems of probability and counting. For instance, how many ways can a standard deck of cards be shuffled? For each of the 52 cards that can end up on the bottom, there are 51 possibilities for ...

Get Sams Teach Yourself Ruby in 21 Days now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.