Related Tags

check
happy
number
how

# How to check if a number is a happy number Educative Answers Team

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:​

$1^2$ + $9^2$ = $82$

$8^2$ + $2^2$ = $68$

$6^2$ + $8^2$ = $100$

$1^2$ + $0^2$ + $0^2$ = $1$

Since we reached 1, 19 is a Happy Number. ## Implementation

The following codes test if a number is a happy or not:

#include <iostream>
using namespace std;

// Utility method to return sum of square of
int numSquareSum(int n)
{
int squareSum = 0;
while (n)
{
squareSum += (n % 10) * (n % 10);
n /= 10;
}
return squareSum;
}

// method return true if n is Happy number
bool isHappynumber(int n)
{
int slow, fast;

// initialize slow and fast by n
slow = fast = n;
do
{
// move slow number by one iteration
slow = numSquareSum(slow);

// move fast number by two iteration
fast = numSquareSum(numSquareSum(fast));

}
while (slow != fast);

// if both number meet at 1, then return true
return (slow == 1);
}

// Driver code to test above methods
int main()
{
int n = 19;
if (isHappynumber(n))
cout << n << " is a Happy number\n";
else
cout << n << " is not a Happy number\n";
}


RELATED TAGS

check
happy
number
how 