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


(*
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. Display an example of your 
output here.
*)
 
local
	fun get_digits 
			(d, s) where (d = 0) = s
		| 	(d, s) = get_digits( d div 10, (d mod 10) :: s)
		| 	n = get_digits( n div 10, [n mod 10] )
	;
	fun mem 
			(x, []) = false
		| 	(x, a :: as) where (x = a) = true
		| 	(x, _ :: as) = mem (x, as)
in
	fun happy
			1 = "happy"
		|	n =
				let 
					val this = (fold (+,0) ` map (fn n = n ^ 2) ` get_digits n);
					val sads = [2, 4, 16, 37, 58, 89, 145, 42, 20]
				in
					if (mem (n,sads)) then
						"unhappy"
					else
						happy this
				end
end
;
 
foreach (fn n = (print n; print " is "; println ` happy n)) ` iota 10;
 