cs-022 — The Shrinking Loop
| Field | Value |
|---|---|
| id | cs-022 |
| difficulty | Foundational |
| topics | tracing, termination |
| lecture | lecture-06 |
| estimated time | 5-minute attempt + 10-minute discussion |
| prerequisites | lectures 1-2 (problem framing, precise pseudocode) |
| objective | recognise the pattern, translate it into precise steps, and trace it correctly |
| solution | held by the instructor; discussed after the attempt |
Problem
A loop divides a number while it is even. How many iterations for a given input, and when does it terminate? Build the trace and the general rule.
Your deliverable is the computed aggregates for the worked instance, the accumulator update rules, and one test input that breaks a careless initialisation. If the problem is ambiguous anywhere, state the assumption you are making and carry on — a stated assumption is part of a good answer.
Examples
- Input: n = 96
- Output: 96->48->24->12->6->3 (stop, odd): 5 divisions, 6 values seen
Solve for the worked instance first. Then ask what would change if one number, name, or condition were replaced by something stranger.
What to notice
- Iterations = number of times 2 divides n. Write n = 2^a * b with b odd; iterations = a.
- Every aggregate here is a small machine: state + update rule.
- The initial value is part of the algorithm, not a detail.
Discussion starter
After the solution is revealed, the class spends five minutes on this prompt: "Where exactly would this solution break first if the input grew to a million items — and would anything break at all?"
Constraints and assumptions
- Difficulty: Foundational (early-semester techniques assumed: precise statements, traces, simple loops).
- Topics: tracing, termination.
- Classroom-scale inputs unless the problem says otherwise.
- Time-box: about five minutes; naming the pattern and stating the assumption is already a pass, completing the calculation is the stretch.
- Optional stretch (not required): describe an alternative approach and say when it beats the obvious one.
Hints and extension
- First nudge: identify the pattern the worked instance uses before computing anything.
- If stuck after three minutes, write the input/output line you expect and trace the smallest example by hand.
- After the reveal, attempt the extension below before the next lecture.
- Extension challenge: Construct an input that maximises the trace length and count the steps exactly.