TheAlgorithms-C-Plus-Plus/others/happy_number.cpp

29 lines
576 B
C++
Raw Normal View History

2017-06-04 18:27:09 +08:00
/* 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 */
// Copyright 2019 TheAlgorithms contributors
2017-06-04 18:27:09 +08:00
#include <iostream>
2018-10-16 20:48:48 +08:00
int main() {
2019-08-21 10:10:08 +08:00
int n, k, s = 0, d;
std::cout << "Enter a number:";
std::cin >> n;
2019-08-21 10:10:08 +08:00
s = 0;
k = n;
while (k > 9) {
while (k != 0) {
2019-08-21 10:10:08 +08:00
d = k % 10;
s += d;
k /= 10;
2017-06-04 18:27:09 +08:00
}
2019-08-21 10:10:08 +08:00
k = s;
s = 0;
2017-06-04 18:27:09 +08:00
}
2019-08-21 10:10:08 +08:00
if (k == 1)
std::cout << n << " is a happy number" << std::endl;
2017-06-04 18:27:09 +08:00
else
std::cout << n << " is not a happy number" << std::endl;
2018-10-16 20:48:48 +08:00
return 0;
2017-06-04 18:27:09 +08:00
}