A happy number is a number that reaches 1 after a sequence of steps. In each step, the number is replaced by the sum of its squared digits.
Let’s test if 19 is a happy number or not:
+ =
+ =
+ =
+ + =
Since we reached 1, 19 is a Happy Number.
The following codes test if a number is a happy or not:
#include <iostream>using namespace std;// Utility method to return sum of square ofint numSquareSum(int n){int squareSum = 0;while (n){squareSum += (n % 10) * (n % 10);n /= 10;}return squareSum;}// method return true if n is Happy numberbool isHappynumber(int n){int slow, fast;// initialize slow and fast by nslow = fast = n;do{// move slow number by one iterationslow = numSquareSum(slow);// move fast number by two iterationfast = numSquareSum(numSquareSum(fast));}while (slow != fast);// if both number meet at 1, then return truereturn (slow == 1);}// Driver code to test above methodsint main(){int n = 19;if (isHappynumber(n))cout << n << " is a Happy number\n";elsecout << n << " is not a Happy number\n";}
Free Resources