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 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
View all Courses