Card 02/ 08

ExampleDifficulty: Beginner2 min

Big O Example: Simplifying 3n² + 5n + 2

As n grows, the largest term takes over and the constants stop mattering.

Turning a cost into its Big O class takes two rules, applied in order: keep the term that grows fastest, then drop its constant factor, the number it is multiplied by. This example applies both to 3n² + 5n + 2 and shows, in numbers, why each rule is safe.

A function that compares items in pairs might do 3n² + 5n + 2 steps on n items. Its three terms grow at different rates. The table shows how much of the total each makes up as n grows.

Each term of 3n² + 5n + 2 at three input sizes, and the share of the total that 3n² makes up, printed by a run
n3n²5n2Total3n² share
1030050235285.23%
10030,000500230,50298.35%
10,000300,000,00050,0002300,050,00299.98%

At n = 10, the two smaller terms are still about 15 per cent of the total. At n = 10,000, 5n is 0.02 per cent and the 2 is under 0.01 per cent. These are lower-order terms: their share keeps shrinking towards nothing, so rule one keeps 3n² alone.

Rule two drops the 3. When n doubles, the total grows 3.70 times from n = 10, 3.97 times from n = 100 and 4.00 times from n = 10,000. That factor of four is what n² does on its own, so the 3 changes how large the cost is, never how it grows. The class is O(n²). Writing O(3n²) is not false, since it is the same growth, but a class is always written in its simplest form.

The two rules apply to any cost written as a sum of terms. Any an² + bn + c with a positive a is O(n²), whatever b and c are. And 7n + 1,000 is O(n), even though the constant is the larger term while n is small, because Big O describes what happens as n grows large.