' ************************************************************
' PROGRAM:      happynum.bac
' PURPOSE:      generate happy numbers
' AUTHOR:               vovchik (Puppy Linux forum)
' COMMENTS:     ported from Rosetta code examples   
' DEPENDS:      gcc, bacon
' PLATFORM:     Puppy Linux (actually, any *nix)
' DATE:         06-12-2011
' NOTES:                see http://en.wikipedia.org/wiki/Happy_number
' 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. :(
' ************************************************************


' ************************
' SUBS & FUNCTIONS
' ************************

' --------------------
FUNCTION is_happy(NUMBER n)
' --------------------
        LOCAL i, j, dig, sum, max_tests TYPE NUMBER
        max_tests = 100
        j = n
        REPEAT
                sum = 0
                WHILE j
                        dig = MOD(j, 10)
                        j = j/10
                        sum = sum + (dig * dig)
                WEND
                IF sum EQ 1 THEN
                        RETURN TRUE
                END IF
                j = sum
                INCR i
        UNTIL i > max_tests
        RETURN FALSE
END FUNCTION

' --------------------
SUB PRINT_HAPPY(NUMBER nums_to_find)
' --------------------
LOCAL i, happy TYPE NUMBER
        i = 1
        happy = 0
        REPEAT
                IF is_happy(i) THEN
                        INCR happy
                        PRINT i
                END IF
                INCR i
        UNTIL happy >= nums_to_find
END SUB

' ************************
' END SUBS & FUNCTIONS
' ************************


' ************************
' MAIN
' ************************

PRINT_HAPPY(20)
END

' ************************
' END MAIN
' ************************