TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
happy_number.cpp
Go to the documentation of this file.
1
7#include <iostream>
8
13template <typename T>
14bool is_happy(T n) {
15 T s = 0; // stores sum of digits
16 while (n > 9) { // while number is > 9, there are more than 1 digit
17 while (n != 0) { // get digit
18 T d = n % 10;
19 s += d;
20 n /= 10;
21 }
22 n = s;
23 s = 0;
24 }
25 return (n == 1) ? true : false; // true if k == 1
26}
27
29int main() {
30 int n;
31 std::cout << "Enter a number:";
32 std::cin >> n;
33
34 if (is_happy(n))
35 std::cout << n << " is a happy number" << std::endl;
36 else
37 std::cout << n << " is not a happy number" << std::endl;
38 return 0;
39}
bool is_happy(T n)
int main()