[387 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.

- Algorithm and Flowchart to find Area of Rhombus using diagonals
- Algorithm and Flowchart to check whether a given number is a duck number or not
- Algorithm and Flowchart for Left Rotation on an Array
- Algorithm to perform Binary to Decimal Conversion
- Pseudocode and flowchart to find the series of S= 1 - 3 + 5 - 7 + 9

- Algorithm and Flowchart to find if a Number is Even or Odd
- Algorithm and Flowchart to find whether a number is Prime Number or Not
- Algorithm and Flowchart for Armstrong Number
- Algorithm for Finding Factorial of a Number
- Algorithm and Flowchart to Calculate Fibonacci series up to n
- How to round a number to nearest integer using python
- Can we have DB table without a primary key?
- Why does everyone hate Java?
- How much JavaScript to learn for Web Development
- How to store password like sensitive information in application