C++ Unhappy Number Program
Definition
What Is an Unhappy Number?
Start with a positive integer and replace it with the sum of the squares of its digits. Repeat. If you reach 1, the number is happy. If you reach the cycle that contains 4, the number is unhappy (sometimes called sad).
Remember
Unhappy cycle:
4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4
2 is unhappy (it reaches 4)
7 is happy (it reaches 1) Approach
How to Check an Unhappy Number
- Require
n > 0. - Replace
nwith the sum of the squares of its digits. - Stop when you see
1(happy) or4(unhappy). Every unhappy chain hits 4. - A set of seen values also works, and it detects any cycle.
Program
C++ Program
Classify one positive integer as happy or unhappy.
C++
#include <iostream>
int squareDigits(int n) {
int sum = 0;
while (n > 0) {
int d = n % 10;
sum += d * d;
n /= 10;
}
return sum;
}
bool isUnhappy(int n) {
while (n != 1 && n != 4)
n = squareDigits(n);
return n == 4;
}
int main() {
int n;
std::cout << "Enter a positive integer: ";
std::cin >> n;
if (n <= 0) {
std::cout << "Enter a positive integer.\n";
return 0;
}
if (isUnhappy(n))
std::cout << n << " is unhappy\n";
else
std::cout << n << " is happy\n";
return 0;
} Frequently Asked Questions
A positive integer whose digit-square chain reaches the cycle containing 4, instead of reaching 1.
Yes. 4 maps to 16, and the chain comes back to 4.
Yes, for this process. A positive integer either reaches 1 or enters the 4-cycle.
Every unhappy chain hits 4, so you do not need to store the whole cycle.
This page starts from positive integers. 0 stays 0, so it is not happy and is not in the 4-cycle.
Next: Harshad Number
Check whether a number is divisible by the sum of its digits.
CODETOFUN NEWS
Stay Ahead in Tech
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
7 people found this page helpful
