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.
But when number is not a happy number it loops endlessly in a cycle which does not include 1.
i have coded happy number problem in python but the problem is when a number is not happy , then how could i stop the iterating cycle. since it will not end with 1 and will keep on repeating itself.
def happynumber(number):
while(number!=1):
numberstr = str(number) #converting a number to string
index=0
sum=0
while(index!=len(numberstr)):
sum = sum + int(numberstr[index])*int(numberstr[index])
index = index+1
print sum
number = sum
return number
You can detect unhappy numbers with a constant amount of memory. According to Wikipedia, for any positive integer starting point, the sequence will terminate at one, or loop forever at
4, 16, 37, 58, 89, 145, 42, 20, 4. Since no other loops exist, it is easy to test for unhappiness.