How to check if a number is a happy number

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

121^2 + 929^2 = 8282

828^2 + 222^2 = 6868

626^2 + 828^2 = 100100

121^2 + 020^2 + 020^2 = 11

Since we reached 1, 19 is a Happy Number.

svg viewer

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";
}
Copyright ©2024 Educative, Inc. All rights reserved