2020-05-28 23:24:14 +08:00
|
|
|
/**
|
2020-05-29 04:43:03 +08:00
|
|
|
* @file
|
|
|
|
* @brief A happy number is a number whose sum of digits is calculated until the
|
|
|
|
* sum is a single digit, and this sum turns out to be 1
|
2020-05-28 23:24:14 +08:00
|
|
|
*/
|
2019-11-28 17:27:27 +08:00
|
|
|
|
2017-06-04 18:27:09 +08:00
|
|
|
#include <iostream>
|
2018-10-16 20:48:48 +08:00
|
|
|
|
2020-05-28 23:24:14 +08:00
|
|
|
/**
|
|
|
|
* Checks if a decimal number is a happy number
|
|
|
|
* \returns true if happy else false
|
|
|
|
*/
|
|
|
|
template <typename T>
|
2020-05-30 07:26:30 +08:00
|
|
|
bool is_happy(T n)
|
|
|
|
{
|
|
|
|
T s = 0; // stores sum of digits
|
|
|
|
while (n > 9)
|
|
|
|
{ // while number is > 9, there are more than 1 digit
|
|
|
|
while (n != 0)
|
|
|
|
{ // get digit
|
2020-05-28 23:24:14 +08:00
|
|
|
T d = n % 10;
|
|
|
|
s += d;
|
|
|
|
n /= 10;
|
|
|
|
}
|
|
|
|
n = s;
|
|
|
|
s = 0;
|
2017-06-04 18:27:09 +08:00
|
|
|
}
|
2020-05-28 23:24:14 +08:00
|
|
|
return (n == 1) ? true : false; // true if k == 1
|
|
|
|
}
|
|
|
|
|
|
|
|
/** Main function */
|
2020-05-30 07:26:30 +08:00
|
|
|
int main()
|
|
|
|
{
|
2020-05-28 23:24:14 +08:00
|
|
|
int n;
|
|
|
|
std::cout << "Enter a number:";
|
|
|
|
std::cin >> n;
|
|
|
|
|
|
|
|
if (is_happy(n))
|
|
|
|
std::cout << n << " is a happy number" << std::endl;
|
|
|
|
else
|
|
|
|
std::cout << n << " is not a happy number" << std::endl;
|
|
|
|
return 0;
|
2017-06-04 18:27:09 +08:00
|
|
|
}
|