TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
happy_number.cpp File Reference

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. More...

#include <iostream>
Include dependency graph for happy_number.cpp:

Go to the source code of this file.

Functions

template<typename T >
bool is_happy (T n)
 
int main ()
 

Detailed Description

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.

Definition in file happy_number.cpp.

Function Documentation

◆ is_happy()

template<typename T >
bool is_happy ( T n)

Checks if a decimal number is a happy number

Returns
true if happy else false

Definition at line 14 of file happy_number.cpp.

14 {
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}

◆ main()

int main ( void )

Main function

Definition at line 29 of file happy_number.cpp.

29 {
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)