Problem. Repeat (even) or (odd). Does every start reach ? (Open conjecture, verified far beyond .) Contest version: compute the number of steps for every start up to .
vector<int> collatzSteps(int N) { // steps to reach 1 for every start <= N (memoized; values may exceed N on the way)
vector<int> s(N + 1, 0);
for (int i = 2; i <= N; i++) {
long long x = i; int c = 0;
while (x >= i) { x = (x % 2) ? 3 * x + 1 : x / 2; c++; }
s[i] = c + s[x];
}
return s;
}| Fact | Value |
|---|---|
| steps from 27 | 111 (peak value 9232) |
| memoization | follow the sequence only until it drops below the start, then reuse the table |
| overflow | intermediate values exceed a lot: use long long |
| cycle detection for variants (, other maps) | Floyd / Brent (Functional Graphs) |
Proof: the memoized loop is correct
For start , the loop follows the sequence until the first value ; every value before that is and not yet tabled, and is already known because . The total steps are the steps taken plus . Termination for each is an empirical fact for this range (it is exactly what the conjecture asserts in general). Checked against direct simulation for all starts up to .