In this article, we will learn about the algorithm and flowchart to check whether a given number is Happy Number or not, followed by a brief explanation of the algorithm for better understanding.
A number is said to be a happy number if it is ultimately equal to 1 after we repeatedly replace the number by the sum of its digits. If we get stuck in an infinite loop, it is not a happy number.
Example: 13, 32, 44, etc.
Let us consider the number 13:
12 + 32 = 10
12 + 02 = 1
Therefore, 13 is a happy number.
Let us consider the number 15:
12 + 52 = 26
22 + 62 = 40
42 + 02 = 16
12 + 62 = 37
32 + 72 = 88
Therefore, as it is getting stuck in an infinite loop, 15 is not a happy number.
In this problem, we need to check whether a given number is a happy number or not. To do so, we need to find out the sum of the square of its digits. If the sum yields 1 after recursive addition, the number is a happy number. If the sum is equal to 4, this means we will get stuck in an infinite loop. Therefore, that number will not be a happy number.
We start the algorithm by taking the number to be checked as user input. The value is then stored in a variable, say ‘n’. We then initialize the sum of the number as ‘n’. A loop is started that runs until the sum is not equal to 1 or 4. Here, we call a predefined function isHappy().
The function isHappy() takes a number num and returns the sum of the square of its digits. If the sum is equal to 1 or 4, the loop terminates. Now, if the sum is equal to 1, the number is a happy number, else if the sum is equal to 4, the number is not a happy number.