Algorithms_in_C++  1.0.0
Set of algorithms implemented in C++.
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:

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.

Function Documentation

◆ is_happy()

template<typename T >
bool is_happy ( n)

Checks if a decimal number is a happy number

Returns
true if happy else false
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

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 }
Here is the call graph for this function:
std::cout
is_happy
bool is_happy(T n)
Definition: happy_number.cpp:14
std::endl
T endl(T... args)
std::cin