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 email@example.com. 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
- Find minimum number to be divided to make a number a perfect square
- 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 a number which give minimum sum when XOR with every number of array of integers
- Number of ways to calculate a target number using only array elements
- Given number of matches played, find number of teams in tournament
- Number of ways to split a binary number such that every part is divisible by 2
- Number of possible permutations when absolute difference between number of elements to the right and left are given
- Number of times the largest perfect square number can be subtracted from N
- Number of ways to divide a given number as a set of integers in decreasing order
- Find the number of positive integers less than or equal to N that have an odd number of digits
- Total number of possible Binary Search Trees using Catalan Number
- Count number of ways to divide a number in 4 parts
- Print a number strictly less than a given number such that all its digits are distinct.