# [Python] Happy numbers Photo by Amine M’Siouri from Pexels

If we take a number, and sum the square of its digits, and then continue this process with the new number, we will either arrive at 1, or we will loop endlessly in a cycle that repeats itself. Those numbers that eventually end up at 1 are called happy numbers.

Consider the number 19. If we square its digits and then add them together, we get:

12 + 92 = 82

Then again:

82 + 22 = 68

Continuing in this fashion, we get:

62 + 82 = 100

And Finally:

12 + 02 + 02 = 1.

Therefore we can say that 19 is a happy number. Now you know who you are inviting for your next party.

So, we want to write a function to check for happy numbers. Here is what the function will do in a nutshell:

1. Receive a number and turn it into string
2. Sum the square of the digits of the number
3. If the resulting number is equal to 1, then it is a happy number.
4. Else if we have not seen the result before (no cycle has formed) continue the process
5. If a cycle is detected, then break the loop. The number is a sad number.

``````"""Econowmics.com"""

#Happy numbers
def happy(n):
"""The function receives a number and returns TRUE if it is a happy number."""

#Turning the number to string
number = str(n)

#container
container = []

#running a for loop to square each digit
while True:
#temporary variable, need to be set zero in each loop
temp = 0
#add each digit squared to the 'temp' variable
for digit in number:
temp += int(digit) ** 2

#After the loop for all digits has ended, now is temp equal to 1? (is it a happy number?)
if temp == 1:
return True
break
#Or, has this number ever occured before? if so, then it is a sad number
elif temp in container:
return False
break
#otherwise, just add it to the container and set the starting number equal to the value of temp
else:
container.append(temp)
number = str(temp)``````

Let us run a quick test to see how much it takes for the function to calculate how many happy numbers are therebelow 1000:

``````#Importing the time module
import time

#Marking the start of time
start= time.time()

#Variable to store the number of happy numbers
count = 0

#Loop to check for happy numbers
for i in range(1,1001):
if happy(i):
count += 1

#Marking the end of time
end = time.time()

#Printing the output to the console
print ('Total happy numbers below 1000: ' + str(count))
print ('It took: ' + str(end-start))``````

Here is the result: 