~/problems / Math & matrices

Happy Number

easy ~15 min

Start from a positive integer and repeatedly replace it with the sum of the squares of its decimal digits. For 19 the chain goes 19 → 82 → 68 → 100 → 1. Some starting numbers reach 1 (and then stay there, since 1² = 1); others loop forever without ever touching 1.

Write reaches_one(n) -> bool that returns True if the chain starting at n reaches 1, and False otherwise.

reaches_one(19)   # True   (19 → 82 → 68 → 100 → 1)
reaches_one(2)    # False  (2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 → ...)
reaches_one(1)    # True
reaches_one(7)    # True
  • 1 <= n <= 2^31 - 1.
  • Aim for O(log n) time per call. Keeping a set of numbers you've seen is fine; the stretch goal is O(1) extra space.
Show hint

if the chain never reaches 1, it must eventually revisit a number it has already produced. How could you notice that without remembering every value?

Topic: Math and matrices. Digit-by-digit arithmetic, matrix rotation and in-place tricks.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc