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


:- module happy.
:- interface.
:- import_module io.
 
:- pred main(io::di, io::uo) is det.
 
:- implementation.
:- import_module int, list, set_tree234.
 
main(!IO) :-
    print_line(get_n_happy_numbers(8, 1), !IO).
 
:- func get_n_happy_numbers(int, int) = list(int).
 
get_n_happy_numbers(NumToFind, N) =
    ( if NumToFind > 0 then
       ( if is_happy(N, init)
       then [N | get_n_happy_numbers(NumToFind - 1, N + 1)]
       else get_n_happy_numbers(NumToFind, N + 1)
       )
    else
       []
    ).
 
:- pred is_happy(int::in, set_tree234(int)::in) is semidet.
 
is_happy(1, _).
is_happy(N, !.Seen) :-
   not member(N, !.Seen),
   insert(N, !Seen),
   is_happy(sum_sqr_digits(N), !.Seen).
 
:- func sum_sqr_digits(int) = int.
 
sum_sqr_digits(N) =
   ( if N < 10 then sqr(N) else sqr(N mod 10) + sum_sqr_digits(N div 10) ).
 
:- func sqr(int) = int.
 
sqr(X) = X * X.