data-structures · intermediate · ~20 min
Recursive recurrence (or the closed-form equivalent) and the importance of using a wide enough integer type.
Count the moves needed to solve the Towers of Hanoi.
Implement unsigned long long hanoi_moves(int n) that returns the number of single-disk moves required to solve the Towers of Hanoi puzzle for n disks. The classic result is 2^n - 1. Either approach is accepted:
T(n) = 2 * T(n-1) + 1, with T(0) = 0.(1ULL << n) - 1ULL.n: the number of disks, 0 <= n <= 60 (so the answer fits in unsigned long long).
unsigned long long: 2^n - 1, the number of moves.
hanoi_moves(0) -> 0
hanoi_moves(1) -> 1
hanoi_moves(3) -> 7
hanoi_moves(10) -> 1023
hanoi_moves(60) -> 1152921504606846975 (2^60 - 1)
n == 0 returns 0.n == 60 is the largest input and must not overflow.unsigned long long. If you use the bit-shift form, shift 1ULL (not 1) so it does not overflow at large n.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: number of disks, in [0, 60].
unsigned long long: 2^n - 1.
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.