Exercise 9 of 30 · beginner · loops · linear · constants
Stepping by three
The code
for i in range(0, n, 3):
work(i)Does skipping elements make it sub-linear?
Count: work calls.
Measured counts
Table
| n | count |
|---|---|
| 8 | 3 |
| 16 | 6 |
| 32 | 11 |
| 64 | 22 |
| 128 | 43 |
| 256 | 86 |
| 512 | 171 |
| 1024 | 342 |
| 2048 | 683 |
| 4096 | 1,366 |
Try to name the class from the shape before opening the answer.
Show the answer and derivation
- Time
- Θ(n)
- Extra space
- O(1)
- Exact count
- ⌈n / 3⌉
- i takes the values 0, 3, 6, …: ⌈n/3⌉ of them.
- n/3 is a constant fraction of n: still Θ(n).
Common mistake: Thinking any skipping is logarithmic. Only a constant factor of the work is skipped.
Check: measured count ÷ (n) settles near 0.333 for large n.