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
13
template
<
typename
T>
14
bool
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
29
int
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
}
is_happy
bool is_happy(T n)
Definition
happy_number.cpp:14
main
int main()
Definition
happy_number.cpp:29
others
happy_number.cpp
Generated by
1.12.0