Editor

Happy Numbers

#270 · Loops · Intermediate · 60 XP · about 10 min

Start with a positive whole number and replace it with the sum of the squares of its digits. Keep doing that. Some numbers end up at 1 and stay there: they are called happy. All the others get stuck in a loop that never reaches 1.

Write is_happy(n) that returns True if n is a happy number and False if it is not.

Examples

is_happy(19)  # returns True
is_happy(4)   # returns False
is_happy(1)   # returns True

19 is happy: 1 + 81 = 82, then 64 + 4 = 68, then 36 + 64 = 100, then 1 + 0 + 0 = 1. 4 is not: it goes to 16, 37, 58, 89, 145, 42, 20 and back to 4, and the loop starts again.

Constraints

  • 1 <= n <= 10 ** 18

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.