A Happy Number n is defined by the following process. Starting with n, replace it with the sum of the squares of its digits, and repeat the process until n equals 1, or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are Happy Numbers, while those that do not end in 1 are unhappy numbers.
First few happy numbers are 1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100
Examples:
Input : 23
Output : Yes
Explanation :
First Iteration:
22 + 32 = 4 + 9 = 13
Second Iteration:
12 + 32 = 1 + 9 = 10
Third Iteration:
12 + 02 = 1 + 0 = 1
Since we reach 1, 23 is Happy.
The idea is simple, we repeated do sum of squares of digits. While doing so, we keep track of visited numbers using a hash. If we reach 1, we return true. Else if we reach a visited number, we return false.
C++
Java
Python 3
C#
Javascript
Output:
Yes
Time complexity: O(log n) for a given number n
Auxiliary Space: O(n)
One important observation is, the cycle always contains 4. So we don’t need to keep track of all numbers. We can simply check for 4.
C++
C
Java
import java.io.*;
class GFG {
static int sumDigitSquare( int n)
{
int sq = 0 ;
while (n != 0 )
{
int digit = n % 10 ;
sq += digit * digit;
n = n / 10 ;
}
return sq;
}
static boolean isHappy( int n)
{
while ( true )
{
if (n == 1 )
return true ;
n = sumDigitSquare(n);
if (n == 4 )
return false ;
}
}
public static void main(String args[])
{
int n = 23 ;
if (isHappy(n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def sumDigitSquare(n) :
sq = 0
while (n) :
digit = n % 10
sq = sq + digit * digit
n = n / / 10
return sq
def isHappy(n) :
while ( 1 ) :
if (n = = 1 ) :
return True
n = sumDigitSquare(n)
if (n = = 4 ) :
return False
return False
n = 23
if (isHappy(n)) :
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static int sumDigitSquare( int n)
{
int sq = 0;
while (n != 0)
{
int digit = n % 10;
sq += digit * digit;
n = n / 10;
}
return sq;
}
static bool isHappy( int n)
{
while ( true )
{
if (n == 1)
return true ;
n = sumDigitSquare(n);
if (n == 4)
return false ;
}
}
static public void Main ()
{
int n = 23;
if (isHappy(n))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function sumDigitSquare(n)
{
let sq = 0;
while (n != 0)
{
let digit = n % 10;
sq += digit * digit;
n = parseInt(n / 10, 10);
}
return sq;
}
function isHappy(n)
{
while ( true )
{
if (n == 1)
return true ;
n = sumDigitSquare(n);
if (n == 4)
return false ;
}
}
let n = 23;
if (isHappy(n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
PHP
Output:
Yes
Time complexity: O(log N) where N is no of digits of a given number n
Auxiliary Space : O(1)
Last Updated :
05 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...