50 XP

72. Happy number

Intermediate sets math

Take a whole number, replace it by the sum of the squares of its digits, and repeat. For 19: 1² + 9² = 82, then 8² + 2² = 68, then 6² + 8² = 100, then 1² + 0² + 0² = 1. A number that reaches 1 this way is called happy.

Other numbers never reach 1: they fall into a loop that goes round forever. 2 goes 4, 16, 37, 58, 89, 145, 42, 20, and back to 4.

Write a function is_happy(n) that takes a whole number n and returns True if it is happy, or False if it ends up in a loop. 1 itself is happy. Your function must stop either way, so it needs a way to notice a loop.

Example 1

Inputn = 19
OutputTrue
Explanation19, 82, 68, 100, 1.

Example 2

Inputn = 2
OutputFalse
Explanation2 reaches 4, which leads round to 4 again.

Example 3

Inputn = 1
OutputTrue
ExplanationAlready at 1.

Constraints

  • n is a whole number from 1 to 10^9.

Submit also runs 9 more tests you can't see.

Practises Sets (lesson 12).

Code
def is_happy(n):
    """Check whether n is a happy number.

    n: int, 1 or more
    Returns: bool, True if the digit-square sums reach 1,
        False if they loop forever
    """
    # Write your code here
    pass