Happy Numbers | A space optimized CPP program to check if a number is happy number ; 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 . ; Keep replacing n with sum of squares of digits until we either reach 1 or we end up in a cycle ; Number is Happy if we reach 1 ; Replace n with sum of squares of digits ; Number is not Happy if we reach 4 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumDigitSquare ( int n ) { int sq = 0 ; while ( n ) { int digit = n % 10 ; sq += digit * digit ; n = n / 10 ; } return sq ; } bool isHappy ( int n ) { while ( 1 ) { if ( n == 1 ) return true ; n = sumDigitSquare ( n ) ; if ( n == 4 ) return false ; } return false ; } int main ( ) { int n = 23 ; if ( isHappy ( n ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; }