THE PUZZLET PAGE

PUZZLET 007 - THE SOLUTION

Puzzlet 007 played with a kind of self-referential integer.  These are numbers which can form themselves by manipulating their own digits in a certain way.  The REMs for the following IBasic computer program contain a description of this particular relationship, followed by code to find the solution.


' Puzzlet #007
' Find integers less than 10,000 which are
' equal to the sum of the cubes of their own
' digits. Repeat the exercise for 4th powers.
' Example: 153 = 1^3 + 5^3 + 3^3.
' By Dave Ellis.


declare sumPowers(i: int , power: int )
def i, power: int
openconsole

for power = 3 to 4
    print "Power ", power, ":  ",
    for i = 1 to 9999
        if i = sumPowers(i, power)
             print i,
        endif
    next
i
    print:print
next
power


print: print "That's all, folks!"
print: print "Press any key to continue ..."
do: until inkey$ <> ""
closeconsole
end


sub sumPowers(i, power)
def L, n, sum: int
def i$: string
i$ = ltrim$(str$ (i))
L = len(i$)
sum = 0
for n = 1 to L
    sum = sum + (val( mid$(i$, n, 1)))^power
next n
return sum

PROGRAM NOTES

Well, that was short and sweet!  The main routine contains two nested loops. The outer loop, using variable power, makes the program run using powers of 3 and then powers of 4, as required.

The inner loop, using iterator i, repeats itself for each of the outer loops.  i runs through all values from 1 to 9999 inclusive to meet the specified values (under 10,000).

At each step, the sum of the powers of i's digits is calculated using the function SumPowers().   The actual power that i is raised to depends on whether the outer loop's variable power is set to 3 or 4 at that particular instant.  

If i is found to be equal to the sum of the powers of its own digits, as returned by SumPowers(), we have a valid solution and it's printed to the screen.  The loops then continue on looking for more solutions until both loops have run their full course.

SumPowers() is a very simple function.  It takes the current values of i and power as its arguments.  Variable i is turned into the string i$ so that its individual digits can be easily accessed for futher processing.

A for-next loop using variable n as its iterator runs through each digit of i$.  At each step of the loop,  the digit is raised to the power specified in variable power and the result added to another variable, sum.  When the loop exits, the value accrued in sum is returned to the calling routine.

When you run the code, it produces the inset screen.

This shows there are five solutions for power 3, and four solutions for power 4, including the trivial solution 1.

Power 3 :  1 153 370 371 407

Power 4 :  1 1634 8208 9474

That's all, folks!

Press any key to continue ...


          

MAIN MENU
DOWNLOAD CODE
ARCHIVES

Site design/maintenance: Dave Ellis E-mail me!
Last Updated: February 22nd, 2004.