Counting Steps
Puzzles often come in two parts. Part one is done in a blink. Part two uses the same rules with much bigger numbers, and the same program suddenly never finishes. To see why, count how many times the code runs, not how many seconds it takes.
Big-O in practice
Big-O notation answers one question: if the input size n is multiplied by 10, what does the work get multiplied by?
| Code shape | Number of steps | Big-O | n × 10 means |
|---|---|---|---|
one loop up to n | n | O(n) | 10× longer |
| a loop inside a loop | about n²/2 | O(n²) | 100× longer |
n halved every step | about log₂ n | O(log n) | only about 3 more steps |
| reading a map or a set | constant | O(1) | no change |
Constants like /2 are dropped in Big-O, because what matters is the shape of the growth.
Why it matters in the browser
The Go runtime in Nibble is an interpreter, roughly tens of times slower than real Go. As a rough guide, assume it does a few million simple steps per second. An O(n) loop with n = 1,000,000 still feels quick. An O(n²) loop with the same n means half a trillion steps: it won't finish, in the browser or on your computer.
Counting without running
Look at this nested loop:
for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
body()
}
}
When i = 0, the body runs n - 1 times. When i = 1, n - 2 times. And so on down to 0. The total is (n-1) + (n-2) + ... + 1 + 0 = n(n-1)/2. That's the number of distinct pairs among n things, a shape that shows up all the time.
For a loop that halves (i /= 2), the number of steps is how many times n can be halved before it reaches 0: 20 steps for a million, 30 for a billion.
Task
Complete three functions that return how many times body() runs in the loop shown in each comment, for the given n:
countA(n int) int: one loop from0ton.countB(n int) int: the nested loop above. Use the formula; don't run the loop.countC(n int) int: the loop that halvesi. A loop is fine here, since it only runs aboutlog₂ ntimes.
For an n of 0 or less, the loops don't run at all. Press Run to see the numbers for n up to a billion.