Happy Number | C / C ++ program to check a number is a Happy number or not ; Utility method to return sum of square of digit of n ; method return true if n is Happy number ; initialize slow and fast by n ; move slow number by one iteration ; move fast number by two iteration ; if both number meet at 1 , then return true ; Driver code to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numSquareSum ( int n ) { int squareSum = 0 ; while ( n ) { squareSum += ( n % 10 ) * ( n % 10 ) ; n /= 10 ; } return squareSum ; } bool isHappynumber ( int n ) { int slow , fast ; slow = fast = n ; do { slow = numSquareSum ( slow ) ; fast = numSquareSum ( numSquareSum ( fast ) ) ; } while ( slow != fast ) ; return ( slow == 1 ) ; } int main ( ) { int n = 13 ; if ( isHappynumber ( n ) ) cout << n << " ▁ is ▁ a ▁ Happy ▁ number STRNEWLINE " ; else cout << n << " ▁ is ▁ not ▁ a ▁ Happy ▁ number STRNEWLINE " ; }