Happy Numbers | Returns sum of squares of digits of a number n . For example for n = 12 it returns 1 + 4 = 5 ; Returns true if n is Happy number else returns false . ; A set to store numbers during repeated square sum process ; Keep replacing n with sum of squares of digits until we either reach 1 or we endup in a cycle ; Number is Happy if we reach 1 ; Replace n with sum of squares of digits ; If n is already visited , a cycle is formed , means not Happy ; Mark n as visited ; Driver code
def sumDigitSquare ( n ) : NEW_LINE INDENT sq = 0 ; NEW_LINE while ( n != 0 ) : NEW_LINE INDENT digit = n % 10 NEW_LINE sq += digit * digit NEW_LINE n = n // 10 NEW_LINE DEDENT return sq ; NEW_LINE DEDENT def isHappy ( n ) : NEW_LINE INDENT s = set ( ) NEW_LINE s . add ( n ) NEW_LINE while ( True ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT n = sumDigitSquare ( n ) NEW_LINE if n in s : NEW_LINE INDENT return False NEW_LINE DEDENT s . add ( n ) NEW_LINE DEDENT return false ; NEW_LINE DEDENT n = 4 NEW_LINE if ( isHappy ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT