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 HappyNumbers;
FROM InOut IMPORT WriteCard, WriteLn;
 
CONST Amount = 8;
VAR seen, num: CARDINAL;
 
PROCEDURE SumDigitSquares(n: CARDINAL): CARDINAL;
VAR sum, digit: CARDINAL;
BEGIN
    sum := 0;
    WHILE n>0 DO
        digit := n MOD 10;
        n := n DIV 10;
        sum := sum + digit * digit;
    END;
    RETURN sum;
END SumDigitSquares;
 
PROCEDURE Happy(n: CARDINAL): BOOLEAN;
VAR i: CARDINAL;
    seen: ARRAY [0..255] OF BOOLEAN;
BEGIN
    FOR i := 0 TO 255 DO 
        seen[i] := FALSE; 
    END;
    REPEAT
        seen[n] := TRUE;
        n := SumDigitSquares(n);
    UNTIL seen[n];
    RETURN seen[1];
END Happy;
 
BEGIN
    seen := 0;
    num := 0;
    WHILE seen < Amount DO
        IF Happy(num) THEN
            INC(seen);
            WriteCard(num,2);
            WriteLn();
        END;
        INC(num);
    END;
END HappyNumbers.