Investigating Happy Numbers

Happy numbers are found by finding the sum of the squares of the digits of the initial test number.
A number is happy if after iteration the sequence terminates on 1

13→1+9=10→1+0=1
So 13 is a happy number because it reaches 1.

2→4→16→37→58→89→145→42→20→4
So 2 is an unhappy number because it ends in a loop.

logolists Help with LOGO list commands.

Logo Investigation

Sum of the squares of the digits

This procedure calculates the sum of the squares of the digits of a number.

to digitsqsum :n
localmake "sum 0
repeat count :n [
make "sum (first :n)*(first :n)+:sum
make "n butfirst :n]
output :sum
end

-count :n counts the number of digits in :n and uses it to control a repeat loop.
-first :n extracts the first digit of :n
-Butfirst then removes the 'used' digit from :n
-output returns the calculated value of the sum to the procedure which initited the procedure call.

This is called and tested using the command.

show digitsqsum 13


Sum Chain

This procedure generates the chain of sums from a given start number.

to digitsqchain :n
localmake "chain []
make "chain fput :n :chain
make "breakflag 0
do.until [
make "n digitsqsum :n
ifelse ( memberp :n :chain) [ make "breakflag 1][ make "chain lput :n :chain]
][ :breakflag=1]
output :chain
end

-:n is entered as the first link in the chain
-the digit square sum is found for :n
-The sum is checked in case it is already a member of the chain.
-If the number is already in the chain then breakflag is made true which ends the do.until loop
-If the number isn't in the chain then the process iterates
-The loop will eventually end at which point the chain is returned.

This is called and tested using the command.

show digitsqchain 13


Searching for Happy Numbers.

This procedure searches up to a given limit.

to digitsqsearch :limit
make "masterlist []
make "masterlist sentence digitsqchain 1 :masterlist
show digitsqchain 1
repeat :limit [
ifelse (memberp repcount+1 :masterlist) [ show repcount+1] [
make "masterlist sentence digitsqchain repcount+1 :masterlist
show digitsqchain repcount+1] ]
end

-masterlist contains all the numbers (happy or sad) which have appeared in any chain.
-as successive chains are created they are added to the masterlist
-numbers are checked against the masterlist to avoid testing numbers which have already appeared in a chain.
-new chains are displayed

This is called and tested using the command.

show digitsqsearch 10


Further Investigations

How many unhappy loops are there? Write a procedure to find all the numbers which belong to the happy or sad chains.

What happens for cubes or other powers higher than 2?

Last modified 29th May 2010