' Puzzlet #055
' A 6 digit integer abcdef is a perfect square.
' abc + 1 = def, so they are consecutive.
' Example: 328,329 = 573^2.
' Are there any more examples like this?
' By Dave Ellis.
declare ConsTriplets (s: int)
declare PrintResult(n: int, s: int)
def num, square: int
openconsole
print "Searching ...": print
num = 317
do
square = num*num
if ConsTriplets(square)
PrintResult(num, square)
endif
num = num + 1
until num > 999
print: print "No more!"
print: print "Press any key ... ",
do: until inkey$ <> ""
closeconsole
end
sub ConsTriplets(s)
' if the second 3 digits of s equal the
' first three digits + 1, returns 1
' otherwise returns 0
def s$: string
def flag, s1, s2: int
s$ = ltrim$(str$(s))
s1 = val(left$(s$,3)): 'extracts left half
s2 = val(right$(s$, 3)): 'extracts right half
if s1 + 1 = s2: ' are they consecutive?
flag = 1
else
flag = 0
endif
return flag
sub PrintResult(n, s)
' pretty printer
print ltrim$(str$(n)), "^2 = ",
print left$(ltrim$(str$(s)),3), ",",
print right$(ltrim$(str$(s)),3)
return
PROGRAM NOTES
We're looking for a 6-digit square here. The fastest way to search for these is to only examine the roots of suitable squares. The smallest 6-digit integer is 1000000, the square root of which is 316.2. We need an integer value (only 3 digits allowed), so the smallest practical root is 317. Using similar reasoning, the maximum will be 999. The program preloads variable num with 317, and runs it through to 999, thus capturing the complete range of possible values.
Within the main DO loop, num2 is stored in variable square. Now num is submitted as parameter to the function ConsTriplets(). This dedicated function splits its argument (held in local variable s) into two halves, using string slicing. If the second half is one greater than the first, a "1" (for TRUE) is returned, otherwise a "0" (for FALSE) is returned to the calling routine.
If a TRUE is returned we have a valid answer, and the main routine prints the result to the screen.
The process continues until all possible square roots have been examined in this way, at which point the program stops.
When you run the code, it generates the screen shown inset.
Thus, there are 3 other answers in addition to the example given.
Searching ...
428^2 = 183,184
573^2 = 328,329
727^2 = 528,529
846^2 = 715,716
No more!
Press any key ...
MAIN MENU
DOWNLOAD CODE
ARCHIVES
Site design/maintenance: Dave Ellis E-mail me!
Last Updated: February 22nd, 2004.