Editor

Python Program to Check a Happy Number

Intermediate · Numbers

A happy number is one that reaches 1 when you keep replacing it with the sum of the squares of its digits. 19 is happy: 1 + 81 = 82, then 64 + 4 = 68, then 36 + 64 = 100, and 1 + 0 + 0 = 1. A number that never reaches 1 gets stuck in a loop and is called unhappy.

Program

happy_number.py
num = 19 # or: num = int(input("Enter a number: "))
seen = set() # numbers already reached, to spot a loop
n = num
steps = [n]
while n != 1 and n not in seen:
seen.add(n)
total = 0
for digit in str(n):
total += int(digit) ** 2
n = total
steps.append(n)
print("Steps:", " -> ".join(str(s) for s in steps))
if n == 1:
print(num, "is a happy number")
else:
print(num, "is not a happy number: it loops back to", n)
Output
Steps: 19 -> 82 -> 68 -> 100 -> 1
19 is a happy number

How it works

  1. Each pass of the while loop replaces n with the sum of the squares of its digits.
  2. An unhappy number never reaches 1: it falls into the same loop of 4, 16, 37, 58, 89, 145, 42 and 20 for ever, so the program needs a way to stop.
  3. The set seen remembers every number reached; if one turns up again, the sequence is going round in circles.
  4. The loop ends either at 1, a happy number, or at a repeat, an unhappy one, and steps shows the whole path.

Other ways to write it

Happy numbers from 1 to 50

Happy numbers from 1 to 50
def is_happy(n):
seen = set()
while n != 1 and n not in seen:
seen.add(n)
n = sum(int(d) ** 2 for d in str(n))
return n == 1
print("Happy numbers from 1 to 50:")
print([n for n in range(1, 51) if is_happy(n)])
Output
Happy numbers from 1 to 50:
[1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49]

With the check inside a function, a list comprehension can collect every happy number in a range.

Floyd's cycle detection, without a set

Floyd's cycle detection, without a set
def next_number(n):
return sum(int(d) ** 2 for d in str(n))
def is_happy(n):
slow = n
fast = next_number(n)
# fast takes two steps for every one step of slow
while fast != 1 and slow != fast:
slow = next_number(slow)
fast = next_number(next_number(fast))
return fast == 1
for n in [19, 4, 7, 20]:
print(n, "is happy" if is_happy(n) else "is not happy")
Output
19 is happy
4 is not happy
7 is happy
20 is not happy

Two pointers walk the same sequence at different speeds; if it loops, the fast one catches the slow one, so nothing has to be remembered. This is a common interview technique.

Try it yourself

Count how many happy numbers there are between 1 and 1000.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises