progress

~/problems / Math & matrices

Happy Number

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

Repeatedly replace a positive integer with the sum of the squares of its digits. Some numbers reach 1 (and stay); others loop forever.

Write reaches_one(n) -> bool that returns whether the chain from n reaches 1.

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. A set of seen numbers is fine; the stretch goal is O(1) extra space. ⭐ Bonus: a speed test earns a star at O(log n) per call.

Show hint

a chain that never reaches 1 must revisit a number. How could you notice 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