One term wins
As n grows, the fastest growing term dominates. The others become a rounding error.
A class is a promise
Naming the class is a claim about large inputs. It is the claim you plan and review against.
A cost class keeps the term that grows fastest and drops the constants. That single name carries the plan for the whole program.
About 2 min of reading
Reduce a total cost to its class.
Loop plus 500 for n of 10.
Before you run it, say out loud what it will print. Then open the answer.
n plus n squared for n of 6.
Before you run it, say out loud what it will print. Then open the answer.
Two per inner turn for n of 5.
Before you run it, say out loud what it will print. Then open the answer.
Halving then full loop for n of 8.
Before you run it, say out loud what it will print. Then open the answer.
Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.
Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.
As n grows, the fastest growing term dominates. The others become a rounding error.
Naming the class is a claim about large inputs. It is the claim you plan and review against.
n = 10
steps = 0
for i in range(n):
steps += 1
steps += 500
print(steps)
The loop plus 500 extra steps is n plus 500. For large n the loop is what matters.
n = 6
steps = 0
for i in range(n):
steps += 1
for i in range(n):
for j in range(n):
steps += 1
print(steps)
n plus n squared. The n squared term grows far faster, so it names the class.
n = 5
steps = 0
for i in range(n):
for j in range(n):
steps += 2
print(steps)
Two steps per inner turn is 2 n squared. The two is dropped, the class is n squared.
n = 8
steps = 0
k = n
while k > 1:
k //= 2
steps += 1
for i in range(n):
steps += 1
print(steps)
log n plus n. The linear part grows faster, so the class is linear.
n = 8
steps = 0
for i in range(n):
k = n
while k > 1:
k //= 2
steps += 1
print(steps)
A halving loop inside a full loop is n times log n. Neither part can be dropped.
print(1, 10, 33, 100, 10000)
For n of 100 the classes are about 1, log n near 7, n log n near 700, n, and n squared at 10000.
n = 100000
print(n, n * n)
A hundred thousand linear is fine, a hundred thousand squared is not. The name decides if the code ships.
Each one is defined here on this site. Open the entry for the full definition and the other words it points at.