Polynomial, Exponential and Factorial Growth
A delivery company has 10 stops. Checking every pair of stops for the shortest link takes a moment. Checking every order in which to visit them means 3,628,800 routes. At 20 stops, the pairs are still easy, but the orders number in the quintillions. Knowing which kind of counting your algorithm does is the difference between "instant" and "never".
The rule
Nested loops give powers; yes-or-no choices give 2ⁿ; orderings give n!.
Three families grow faster than linear:
- Polynomial, like n² or n³. Comes from loops inside loops over the input. Comparing every item with every other item is about n².
- Exponential, 2ⁿ. Comes from making an independent yes-or-no choice for each item: every subset of n items. Each extra item doubles the work.
- Factorial, n! = n × (n − 1) × … × 1. Comes from trying every ordering of n items. Each extra item multiplies the work by the new n.
The numbers pull apart fast:
| n | n² | 2ⁿ | n! |
|---|---|---|---|
| 5 | 25 | 32 | 120 |
| 10 | 100 | 1,024 | 3,628,800 |
| 20 | 400 | 1,048,576 | about 2.4 × 10¹⁸ |
Put the whole ladder together, slowest-growing first: 1, log n, n, n log n, n², n³, 2ⁿ, n!.