cs-087 — Power by Halving
| Field | Value |
|---|---|
| id | cs-087 |
| difficulty | Intermediate |
| topics | divide and conquer, analysis |
| lecture | lecture-22 |
| estimated time | 5-minute attempt + 10-minute discussion |
| prerequisites | loops, lists, and tracing from lectures 1-6 |
| objective | choose the technique, trace it faithfully, and defend the boundary behaviour |
| solution | held by the instructor; discussed after the attempt |
Problem
Compute x^n with O(log n) multiplications by halving the exponent. Divide-conquer-combine, with a trace that shows the saving.
Your deliverable is the recurrence with base cases, the answer for the worked instance, and the memoised (or tabulated) version. 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: 2^10 -> 4 multiplications (vs 9 naive); 2^100 -> ~7 (vs 99)
- Output: x^n = x^(n/2) squared; odd n costs one extra multiply; trace shows the saving
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
- One sentence: 'compute the half power once, square it'. The trace proves the log-n claim.
- Trust the recursive call: if f(smaller) is correct, the transition is all you must get right.
- A DP table is the call tree, cached.
Discussion starter
After the solution is revealed, the class spends five minutes on this prompt: "Where does the memory go in the memoised version, and what is the trade?"
Constraints and assumptions
- Difficulty: Intermediate (loops and lists assumed).
- Topics: divide and conquer, analysis.
- Classroom-scale inputs unless the problem says otherwise.
- Time-box: about five minutes for the plan and trace; finishing the details is a bonus, defending the method is the target.
- 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: Convert the recursion to a loop and compare the call stacks.