' Puzzlet #060
' Find a 4-digit integer which is equal to
' the sum of the 4th powers of its own digits.
' Example: 1634 = 1^4 + 6^4 + 3^4 + 4^4 = 1634.
' Are there any others like this?
' By Dave Ellis.
declare Sum4thPowers(n: int)
declare PrintResult(n: int)
def num: int
openconsole
print "Searching ...": print
for num = 1000 to 9999
if Sum4thPowers(num) = num
PrintResult(num)
endif
next num
print: print "No More!"
print: print "Press any key ... ",
do: until inkey$ <> ""
closeconsole
end
sub Sum4thPowers(n)
' returns the sum of the 4th powers of
' the individual digits of n
def it, sum: int
def n$: string
n$ = str$(n)
sum = 0
for it = 2 to 5
sum = sum + (val(mid$(n$, it, 1)))^4
next it
return sum
sub PrintResult(n)
' pretty printer
def it, sum: int
def n$: string
n$ = str$(n)
sum = 0
for it = 2 to 5
print mid$(n$, it, 1), "^4 ",
if it < 5
print "+ ",
else
print "= ",
endif
next it
print "(",
for it = 2 to 5
print ltrim$(str$(val(mid$(n$, it, 1))^4)),
if it < 5
print " + ",
else
print ") = ",
endif
next it
print n: print
return
PROGRAM NOTES
Variable num is used to iterate through all possible 4-digit integers. Every integer is submitted to the function Sum4thPowers(). The sum of the fourth powers of the individual digits of num is returned. If this is the same as num itself, we have a solution, and it's printed out to the screen.
Sum4thPowers() is a very simple function. The argument n is the local variable name for num. n is converted into string form and stored in n$. Iterator it is used to work through n$'s characters one at a time. At each iteration, the line sum = sum + (val(mid$(n$, it, 1)))^4 is applied. The mid$ expressiobn isoles the required character. val converts it back to an integer, which is then raised to the fourth power and added to a variable created for storing totals, sum. When all the characters have been processed, the contents of sum are returned to the calling routine.
The PrintResult() subroutine is included to give a neat layout of the results on your screen. The expression print ltrim$(str$(val(mid$(n$, it, 1))^4)) isn't as complicated as it sounds! Everthing from val onwards is as already explained in the previous paragraph. The result is turned back into a string format and the leading space removed by ltrim$ to make tidier printing.
When you run the code, you'll see the following on your screen. There are three results altogether, including the one given in the example.
Searching ...
1^4 + 6^4 + 3^4 + 4^4 = (1 + 1296 + 81 + 256) = 1634
8^4 + 2^4 + 0^4 + 8^4 = (4096 + 16 + 0 + 4096) = 8208
9^4 + 4^4 + 7^4 + 4^4 = (6561 + 256 + 2401 + 256) = 9474
No more!
Press any key to exit ...
MAIN MENU
DOWNLOAD CODE
ARCHIVES
Site design/maintenance: Dave Ellis E-mail me!
Last Updated: February 22nd, 2004.