' Puzzlet #074.
' To find all cases where summing the
' squares of two different integers,
' each less than four digits in length,
' generates a consecutive run of digits.
' Example: 100^2 + 116^2 = 23456
' By Dave Ellis.
declare IsARun(f: int)
declare PrintResult()
def num1, num2, sumSquares: int
openconsole
print "Searching ...": print
print "nr1 nr2 sumSquares": print
for num1 = 1 to 998
for num2 = num1 + 1 to 999
sumSquares = num1^2 + num2^2
if IsARun(sumSquares)
PrintResult()
endif
next num2
next num1
print: print "No more!"
print: print "Press any key ... ",
do: until inkey$ <> ""
closeconsole
end
sub IsARun(f)
' If the integers of f are in continuous ascending
' order, regardless of length or starting digit,
' return -1, otherwise return 0.
def flag, i, L: int
f$ = ltrim$(str$(f))
q$=left$(f$, 1)
L = len(f$)
i = 1
flag = -1
do
r$ = mid$(f$, i+1, 1)
if val(r$) - val(q$) <> 1
flag = 0
endif
i = i + 1
q$ = r$
until flag = 0 | i = L
return flag
sub PrintResult
' pretty printer
print using ("###", num1),
print using ("#####", num2),
print using ("##########", sumSquares)
return
PROGRAM NOTES
The two integers to be squared are held in variables num1 and num2. The sum of their squares in held in variable sumSquares.
Two nested FOR-NEXT loops extract all possible combinations of two different values for num1 and num2. For each combination, the sum of the squares is calculated and stored in sumSquares using the line sumSquares = num1^2 + num2^2.
sumSquares is now submitted as the parameter to the function IsARun(). If the integers of sumSquares are in continuous ascending
order, regardless of length or starting digit, IsARun() returns -1 (TRUE), otherwise it returns 0 (FALSE).
Whenever a TRUE is returned, we have a valid solution, and it's printed out to the screen neatly using the subroutine PrintResult(). The process then continues until all values of num1 and num2 have been examined.
When the program is run, it generates the inset screen.
As you can see, there's a very nice selection of answers, ranging in length from two digits to five.
Searching ...
nr1 nr2 sumSquares
3 5 34
3 6 45
3 15 234
3 35 1234
5 8 89
50 233 56789
100 116 23456
167 170 56789
No more!
Press any key ...
Site design/maintenance: Dave Ellis E-mail me!
Last Updated: February 22nd, 2004.