| ' Puzzlet #094 ' Find three consecutive odd integers ' all less than 100 such that the sum of ' their squares is a unidigital number ' (i.e., all its digits are the same). ' By Dave Ellis. declare AllDigitsSame(n: int) declare PrintResult() def i, sumSquares: int openconsole color 11, 0: cls print " Searching ...": print color 14, 0 for i = 1 to 95 #2 sumSquares = 3*i*2 + 12*i + 20 if AllDigitsSame(sumSquares) PrintResult() endif next it1 color 11, 0 print: print " No more!" print: print " Press a key to exit ... ", do: until inkey$ <> "" closeconsole end sub AllDigitsSame(n) ' if all the digits in argument n are ' identical returns -1, else returns 0 def flag, i, L: int n$ = ltrim$(str$(n)) f$= left$(n$,1) L = len(n$) i = 2 flag = -1 do if mid$(n$,i,1) <> f$ flag = 0 endif i = i + 1 until flag = 0 | i > L return flag sub PrintResult ' pretty printer print str$(i), chr$(253), " +", print str$(i + 2), chr$(253), " +", print str$(i + 4), chr$(253), " = ", print sumSquares return |
| PROGRAM NOTES As usual, we need to define the search range before we write any code. We're looking for three consecutive odd integers, all less than 100. the highest odd integer possible is thus 99, so the other two in the highest triplet must be 97 and 95. The range for the lowest value in the triplet is thus 1 to 95. In the main FOR-NEXT loop, variable i is used as an iterator over the range 1 to 95, as derived above. Note that each iteration skips 2, since only odd integers are of interest here. We need to find the sum of the squares of i, i + 2, and i + 4. Using a little algebra, i2
+ (i + 2)2
+ (i + 4)2 = 3i2
+ 12i + 20
At each iteration, this formula is applied to the current value of i and the result saved in variable sumSquares. sumSquares is submitted as the parameter to function AllDigitsSame[], whose job is return -1 (TRUE) if all the digits of its argument are identical, or 0 (FALSE) otherwise. If AllDigitsSame[] returns TRUE, the current values of it1, it2, and it3 are printed to the screen using subroutine PrintResults(). Then the main FOR-NEXT loop continues until it1 is greater than 95. |
| When
you run the program, you'll see the inset result printed out onto your
computer's screen. This is the only solution. |
|
Searching
... 41² + 43² + 45² = 5555 No more! Press a key to exit ... |