A number is called happy if it leads to 1 after a sequence of steps where in each step number is replaced by sum of squares of its digit that is if we start with Happy Number and keep replacing it with digits square sum, we reach 1.
Input: n = 19 Output: True 19 is Happy Number, 1^2 + 9^2 = 82 8^2 + 2^2 = 68 6^2 + 8^2 = 100 1^2 + 0^2 + 0^2 = 1 As we reached to 1, 19 is a Happy Number. Input: n = 20 Output: False
A number will not be a Happy Number when it makes a loop in its sequence that is it touches a number in sequence which already been touched. So to check whether a number is happy or not, we can keep a set, if same number occurs again we flag result as not happy. A simple function on above approach can be written as below –
We can solve this problem without using extra space and that technique can be used in some other similar problem also. If we treat every number as a node and replacement by square sum digit as a link, then this problem is same as finding a loop in a linklist :
So as proposed solution from above link, we will keep two number slow and fast both initialize from given number, slow is replaced one step at a time and fast is replaced two steps at a time. If they meet at 1, then the given number is Happy Number otherwise not.
13 is a Happy Number
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Happy Numbers
- Number of factors of very large number N modulo M where M is any prime number
- Count number of trailing zeros in Binary representation of a number using Bitset
- Count number of triplets with product equal to given number with duplicates allowed
- Find minimum number to be divided to make a number a perfect square
- Number of possible permutations when absolute difference between number of elements to the right and left are given
- Largest number dividing maximum number of elements in the array
- Smallest number dividing minimum number of elements in the Array
- Smallest number dividing minimum number of elements in the array | Set 2
- Number of times the largest perfect square number can be subtracted from N
- Number of ways to calculate a target number using only array elements
- Find the number of positive integers less than or equal to N that have an odd number of digits
- Find smallest possible Number from a given large Number with same count of digits
- Find a number which give minimum sum when XOR with every number of array of integers
- Minimum divisor of a number to make the number perfect cube