[1788 views]

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:

1^{2} + 3^{2} = 10

1^{2} + 0^{2} = 1

Therefore, 13 is a happy number.

Let us consider the number 15:

1^{2} + 5^{2} = 26

2^{2} + 6^{2} = 40

4^{2} + 0^{2} = 16

1^{2} + 6^{2} = 37

3^{2} + 7^{2} = 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.

- Java IDE Online
- Python IDE Online
- JSON Formatter/Minifier Online
- Case Converter
- Reverse String
- HTML Encoder
- HTML Decoder
- URL Encoder
- URL Decoder
- Decimal To Binary
- Binary To Decimal
- Decimal To Octal
- Binary To Octal
- Decimal To Hexadecimal
- Hexadecimal To Decimal
- Hexadecimal To Binary
- Octal To Decimal
- Octal to Hexadecimal
- Octal to Binary
- Calculate String Length
- Remove Spaces
- Remove Line Breaks
- Remove Empty Lines
- Remove Duplicate Lines
- Word Counter
- Replace Space with hyphen
- Check Armstrong number
- Text to URL

- Algorithm and Flowchart to Check whether a number is a Perfect Square
- Prefix to Infix notation Algorithm and Flowchart
- Algorithm and Flowchart to find the prime factors of a number
- Algorithm and Flowchart for N Queen Problem with Simple Explanation
- Algorithm and flowchart to find Frequency of Characters in Sentence