data-structures · intermediate · ~20 min
Recursive recurrence (or the closed-form equivalent) and the importance of using a wide enough integer type.
Implement unsigned long long hanoi_moves(int n) that returns the number of single-disk moves required to solve Towers of Hanoi for n disks (0 <= n <= 60).
The classic result: it takes 2^n - 1 moves. You can implement either:
T(n) = 2 * T(n-1) + 1, T(0) = 0.(1ULL << n) - 1ULL.Either solution is acceptable.
hanoi_moves(0) -> 0
hanoi_moves(1) -> 1
hanoi_moves(2) -> 3
hanoi_moves(3) -> 7
hanoi_moves(10) -> 1023
hanoi_moves(60) -> 1152921504606846975 // 2^60 - 1
0 <= n <= 60 (so the answer fits in unsigned long long).n == 0 → 0.n == 60 → just below ULLONG_MAX / 16.Towers of Hanoi is the cleanest demonstration of recursive thinking: to move n disks, first move n-1 to the spare peg, move the largest, then move n-1 back. The closed-form solution (2^n - 1) emerges naturally — a small but real example of how recursion solves exponential problems compactly.
n in [0, 60].
2^n - 1 as unsigned long long.
Use unsigned long long. Recursive or closed-form both fine.
#include <stdint.h>
unsigned long long hanoi_moves(int n) { /* TODO */ return 0; }
Returning int — overflows at n == 31. Forgetting that recursion past about n == 25 takes noticeable time without memoisation. The closed form is fastest.
n == 0; n == 60; n == 1.
Recursive: O(2^n) — but only because the recurrence does 2 calls each level. Closed form: O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.