From cc5ce16b5874ec33c3b3fb5fc48188d91bf4987c Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Thu, 28 May 2020 11:24:14 -0400 Subject: [PATCH] document happy numbers --- others/happy_number.cpp | 57 ++++++++++++++++++++++++----------------- 1 file changed, 34 insertions(+), 23 deletions(-) diff --git a/others/happy_number.cpp b/others/happy_number.cpp index 7d25a1bbd..dacb2b8c4 100644 --- a/others/happy_number.cpp +++ b/others/happy_number.cpp @@ -1,28 +1,39 @@ -/* 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 +/** + * A [happy number](https://en.wikipedia.org/wiki/Happy_number) is a decimal + * number whose sum of digits is calculated until the sum is a single digit, and + * this sum turns out to be 1. + */ #include -int main() { - int n, k, s = 0, d; - std::cout << "Enter a number:"; - std::cin >> n; - s = 0; - k = n; - while (k > 9) { - while (k != 0) { - d = k % 10; - s += d; - k /= 10; +/** + * Checks if a decimal number is a happy number + * \returns true if happy else false + */ +template +bool is_happy(T n) { + T s = 0; // stores sum of digits + while (n > 9) { // while number is > 9, there are more than 1 digit + while (n != 0) { // get digit + T d = n % 10; + s += d; + n /= 10; + } + n = s; + s = 0; } - k = s; - s = 0; - } - if (k == 1) - std::cout << n << " is a happy number" << std::endl; - else - std::cout << n << " is not a happy number" << std::endl; - return 0; + return (n == 1) ? true : false; // true if k == 1 +} + +/** Main function */ +int main() { + int n; + std::cout << "Enter a number:"; + std::cin >> n; + + if (is_happy(n)) + std::cout << n << " is a happy number" << std::endl; + else + std::cout << n << " is not a happy number" << std::endl; + return 0; }