A number is happy if repeatedly replacing it with the sum of the squares of its digits eventually reaches 1. Otherwise it loops forever in a cycle without 1. Return whether n is happy.
The sequence is a linked list of numbers. Move slow one step and fast two steps; they meet inside the cycle. The number is happy exactly when that cycle is 1 → 1.
1function isHappy(n: number): boolean {2const next = (x: number) => [...String(x)].reduce((s, d) => s + Number(d) ** 2, 0);3let slow = n, fast = next(n);4while (fast !== 1 && slow !== fast) {5slow = next(slow); fast = next(next(fast));6}7return fast === 1;8}
slow = 19, fast = 82.
Space: play/pause · ←/→: step