THE PUZZLET PAGE

PUZZLET 031 - THE SOLUTION

'  Puzzlet #031.
'  The product of two integers is equal to its
'  sum reversed.  All numbers used are less than
'  1,000.  Example:  24 x 3 = 27.  24 + 3 = 72.
'  Can you find any more like this?
'  By Dave Ellis.


declare Reversed()
declare PrintResult()
def it1, it2: int
def flag, prod, sum: int
openconsole
print
"Searching ...": print
it1 = 1

do
    it2 = it1
    flag = 0
    do
        prod = it1 * it2
        if prod > 999: ' too big
            flag = 1
        else
            sum = it1 + it2
            if Reversed(): ' is sum prod reversed?
                PrintResult()
            endif
        endif

        it2 = it2 + 1
    until flag | it2 > 999
    it1 = it1 + 1
until it1 > 499

print: print "No more!"
print: print "Press a key to exit ...",
do: until inkey$ <> ""
closeconsole
end


sub Reversed
' if prod is a reversal of sum, returns 1,
' otherwise returns 0.

def flag, i, L: int
def prod$, rev$, sum$: string
sum$ = ltrim$(str$(sum))
prod$ = ltrim$(str$(prod))
L = len(prod$)
' create rev$ to hold prod$ reversed
rev$ = ""
for i = L to 1 #-1
    rev$ = rev$ + mid$(prod$, i, 1)
next i
if rev$ <> sum$
    flag = 0
else
    flag = 1
endif
return
flag

sub PrintResult
' pretty printer
print it1, "+ ",
print using ("###", it2), " = ",
print using ("###", sum), "  :",
print using ("###", it1), " x ",
print using ("###", it2), " = ",
print using ("###", prod)
return


PROGRAM NOTES

The variables it1 and it2 are used to generate all valid integer values required within the range. it2 is always larger than it1, but never exceeds 999, since at this value it will always exceed 999 when summed with it1. Likewise, it1 is never permited to exceed 500, since at this value it2 must be at least 500, giving a sum of 999.

The outer DO loop initialises the values of it1, it2, and flag. The inner DO loop begins by calculating the product it1*it2 and storing it in variable prod. If this exceeds 999, the loop is exited and the next value of it1 tried.

If the product doesn't exceed 999, it1 and it2 are added together and the sum stored in variable sum. Subroutine Reversed() can now be called. If prod is a reversal of sum, Reversed() returns 1 (TRUE), otherwise 0 (FALSE).

Whenever TRUE is returned, we have a valid solution and PrintIt() is invoked to print the results to the screen. After the test for reversal, and printing if appropriate, the looping continues until all legal pairs of integers have been processed.


When you run the code,  it will produce the inset screen.  

There are five solutions in total.


Searching ...

2 +     2  =     4  :  2  x    2 =     4
2 +   47  =   49  :  2  x   47 =   94
2 + 497  =  499  :  2  x 497 = 994
3 +   24  =   27  :  3  x   24 =   72
9 +     9  =   18  :  9  x     9 =   81


No more!

Press a key to exit ...

          


MAIN MENU
DOWNLOAD CODE
ARCHIVES


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