From Wikipedia, the free encyclopedia:

 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 end in   1   are       happy   numbers,   
 while   those numbers   that   do   not   end in   1   are   unhappy   numbers. 


Task

Find and print the first   8   happy numbers.

Display an example of your output here on this page.



See also

   The OEIS entry:   The     happy numbers:   A007770
   The OEIS entry:   The unhappy numbers;   A031177


include :set
 
happiness = set.new 1
sadness = set.new
 
sum_of_squares_of_digits = { num |
  num.to_s.dice.reduce 0 { sum, n | sum = sum + n.to_i ^ 2 }
}
 
happy? = { n, seen = set.new |
  when {true? happiness.include? n } { happiness.merge seen << n; true }
    { true? sadness.include? n } { sadness.merge seen; false }
    { true? seen.include? n } { sadness.merge seen; false }
    { true } { seen << n; happy? sum_of_squares_of_digits(n), seen }
}
 
num = 1
happies = []
 
while { happies.length < 8 } {
  true? happy?(num)
    { happies << num }
 
  num = num + 1
}
 
p "First eight happy numbers: #{happies}"
p "Happy numbers found: #{happiness.to_array.sort}"
p "Sad numbers found: #{sadness.to_array.sort}"