#include using namespace std; /* * This C++ program determines if a number is happy or unhappy. * * @creator g.d.thurman * @created 2008.03.08 */ int main(int argc, char* argv[]) { int n; bool ishappy(int); for (int i = 1; i < argc; i++) { if ((n = atoi(argv[i])) > 0) cout << n << " is " << (ishappy(n) ? "happy" : "unhappy") << endl; } return 0; } /* * NumberGossip.com defines "happy number" as follows: "One can take * the sum of the squares of the digits of a number. Those numbers are * happy for which iterating this operation eventually leads to 1." */ bool ishappy(int n) { int sum_digits_squared(int); while ((n = sum_digits_squared(n)) > 0) { if (n == 1) return true; if (n == 4) return false; // concerned about infinite loop } return false; } /* * Sum the square of the digits of 'n'. Example: if n == 216, * return 41 (2-squared + 1-squared + 6-squared [4 + 1 + 36]). */ int sum_digits_squared(int n) { int sum = 0, a, orig = n; while (n > 0) { a = n % 10; sum = sum + a * a; n = n / 10; } return sum; }