VOOZH about

URL: https://www.geeksforgeeks.org/dsa/happy-number/

⇱ Happy Number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Happy Number

Last Updated : 2 Sep, 2024

A number is called happy if it leads to 1 after a sequence of steps wherein each step number is replaced by the 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. 

Examples :

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 the same number occurs again we flag result as not happy. A simple function on the above approach can be written as below –  

Complexity Analysis:

Time Complexity: O(n*log(n)). 
Auxiliary Space: O(n) since using extra set for storage

We can solve this problem without using extra space and that technique can be used in some other similar problems 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 a proposed solution from the above link, we will keep two numbers slow and fast both initialize from a 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.  

Output :

13 is a Happy Number

Complexity Analysis:

Time Complexity: O(n*log(n)).
Auxiliary Space: O(1). 


Another approach for solving this problem using no extra space.
A number cannot be a happy number if, at any step, the sum of the square of digits obtained is a single-digit number except 1 or 7. This is because 1 and 7 are the only single-digit happy numbers. Using this information, we can develop an approach as shown in the code below - 


Output
13 is a Happy number

Complexity Analysis:

Time Complexity: O(n*log(n)).
Auxiliary Space: O(1). 

See your article appearing on the GeeksforGeeks' main page and help other Geeks.

Comment
Article Tags:
Article Tags: