21
2
A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers (or sad numbers). Given a number print whether it is happy or unhappy.
Sample Inputs
7
4
13
Sample Outputs
Happy
Unhappy
Happy
Note: Your program should not take more than 10 secs for any number below 1,000,000,000.
Ok, so I kinda get how this works (Literally taking each number, splitting it and adding the square of each digit), but what's with the stop condition of (a < 5) and using (a < 2) to decide if it's happy or not? I don't question the validity, just the logic. – Mr. Llama – 2011-04-25T22:42:08.210
2
That is the same as
– Casey – 2011-04-25T23:57:27.147a <= 4
anda <= 1
. If the cycle has a 1 in it then it is happy, and if it has a 4 in it, then it is not happy. See the wikipedia section about the unhappy cycle. So once the value ofa
is 4 or less, he checks if a is -- the result of that is your answer.