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
Steps: 19 -> 82 -> 68 -> 100 -> 1 19 is a happy number
How it works
- Each pass of the
whileloop replacesnwith the sum of the squares of its digits. - 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.
- The set
seenremembers every number reached; if one turns up again, the sequence is going round in circles. - The loop ends either at 1, a happy number, or at a repeat, an unhappy one, and
stepsshows the whole path.
Other ways to write it
Happy numbers from 1 to 50
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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises