Explanation
In this program, we need to determine whether a given number is a happy number or not.
Happy number
The happy number can be defined as a number which will yield 1 when it is replaced by the sum of the square of its digits repeatedly. If this process results in an endless cycle of numbers containing 4, then the number is called an unhappy number.
For example, 32 is a happy number as the process yields 1 as follows
32 + 22 = 13
12 + 32 = 10
12 + 02 = 1
Some of the other examples of happy numbers are 7, 28, 100, 320 and so on.
The unhappy number will result in a cycle of 4, 16, 37, 58, 89, 145, 42, 20, 4, ....
To find whether a given number is happy or not, calculate the square of each digit present in number and add it to a variable sum. If resulting sum is equal to 1 then, given number is a happy number. If the sum is equal to 4 then, the number is an unhappy number. Else, replace the number with the sum of the square of digits.
Algorithm
- isHappyNumber() determines whether a given number is happy or not.
- If the number is greater than 0, then calculate remainder rem by dividing the number with 10.
- Calculate square of rem and add it to a variable sum.
- Divide number by 10.
- Repeat the steps from a to c till the sum of the square of all digits present in number has been calculated.
- Finally, return the sum.
- Define and initialize variable num.
- Define a variable result and initialize it with a value of num.
- If the result is neither equal to 1 nor 4 then, make a call to isHappyNumber().
- Otherwise, if the result is equal to 1 then, given number is a happy number.
- If the result is equal to 4 then, given number is not a happy number.
Input:
num = 82
Output:
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
82 is a happy number number
Python
Output:
C
Output:
JAVA
Output:
C#
Output:
PHP
Output: