A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n.

(Munchausen is also spelled: Münchhausen.)

For instance:    3435 = 33 + 44 + 33 + 55 



Task
Find all Munchausen numbers between   1   and   5000.



Also see

 The OEIS entry:  A046253
 The Wikipedia entry:  Perfect digit-to-digit invariant, redirected from Munchausen Number


#COMPILE EXE
#DIM ALL
#COMPILER PBCC 6
 
DECLARE FUNCTION GetTickCount LIB "kernel32.dll" ALIAS "GetTickCount"() AS DWORD
 
FUNCTION PBMAIN () AS LONG
LOCAL i, j, n, sum, ten1, ten2, t AS DWORD
LOCAL n0, n1, n2, n3, n4, n5, n6, n7, n8, n9 AS DWORD
LOCAL s1, s2, s3, s4, s5, s6, s7, s8 AS DWORD
DIM pow(9) AS DWORD, num(9) AS DWORD
LOCAL pb AS BYTE PTR
LOCAL number AS STRING
 
  t = GetTickCount()
  ten2 = 10
  FOR i = 1 TO 9
    pow(i) = i
    FOR j = 2 TO i
      pow(i) *= i
    NEXT j
  NEXT i
  FOR n = 1 TO 11
    FOR n9 = 0 TO n
      FOR n8 = 0 TO n - n9
        s8 = n9 + n8
        FOR n7 = 0 TO n - s8
          s7 = s8 + n7
          FOR n6 = 0 TO n - s7
            s6 = s7 + n6
            FOR n5 = 0 TO n - s6
              s5 = s6 + n5
              FOR n4 = 0 TO n - s5
                s4 = s5 + n4
                FOR n3 = 0 TO n - s4
                  s3 = s4 + n3
                  FOR n2 = 0 TO n - s3
                    s2 = s3 + n2
                    FOR n1 = 0 TO n - s2
                      n0 = n - (s2 + n1)
                      sum = n1 * pow(1) + n2 * pow(2) + n3 * pow(3) + _
                            n4 * pow(4) + n5 * pow(5) + n6 * pow(6) + _
                            n7 * pow(7) + n8 * pow(8) + n9 * pow(9)
                      SELECT CASE AS LONG sum
                      CASE ten1 TO ten2 - 1
                        number = LTRIM$(STR$(sum))
                        pb = STRPTR(number)
                        MAT num() = ZER
                        FOR i = 0 TO n -1
                          j = @pb[i] - 48
                          INCR num(j)
                        NEXT i
                        IF n0 = num(0) AND n1 = num(1) AND n2 = num(2) AND _
                           n3 = num(3) AND n4 = num(4) AND n5 = num(5) AND _
                           n6 = num(6) AND n7 = num(7) AND n8 = num(8) AND _
                           n9 = num(9) THEN CON.PRINT STR$(sum)
                      END SELECT
                    NEXT n1
                  NEXT n2
                NEXT n3
              NEXT n4
            NEXT n5
          NEXT n6
        NEXT n7
      NEXT n8
    NEXT n9
    ten1 = ten2
    ten2 *= 10
  NEXT n
  t = GetTickCount() - t
  CON.PRINT "execution time:" & STR$(t) & " ms; hit any key to end program"
  CON.WAITKEY$
END FUNCTION