[Home] [Puzzles & Projects] [Delphi Techniques] [Math topics] [Library] [Utilities]


Problem DescriptionA Magic Square is of order N is an NxN matrix containing the integers from1 to N^{2 }arranged so that the sum of each row, column and the cornertocorner diagonal are all equal. Write a program to create Magic Squares of odd order (1,3,5,7, etc.) up to order 51. Background & Techniques For small squares we could use the brute force approach as used in the 3x3 matrix in the rotating sums problem. But recall from earlier exercises that there are X! ways to arrange X numbers and 10! is approaching the upper limit that can be solved quickly (10! is about 3.6 million). This implies that finding the solution by brute force for an order 5 square would require trying up to 25! permutations of the numbers from 1 to 25. Clearly not a practical approach. Like many puzzles of a mathematical bent, Magic Squares have been studied for hundreds of years. The algorithm used here for odd order Magic Squares was discovered at least 500 years ago. I'll leave it to the reader to search out the pertinent history. There's the algorithm: "Start with 1 in the middle of the top row; then go up and left assigning numbers in increasing order to empty cells; if you fall off of the square imagine the same square as tiling the plane and continue; if a cell is occupied, move down instead and continue." From that statement, the implementation is straightforward. A couple of tricks are applied to the StringGrid used to display the results. The individual cell sizes are adjusted to contain the maximum values for a particular square. The font is set to size 8 if numbers greater than 100 need to be displayed and to size 12 for smaller squares. The C function is used to set the cell width and height for the maximum value at this font size. Finally the overall grid size is adjust to be just large enough to contain the cells (plus gridlines). The program only has about 60 user coded statements, so we'll classify it as Beginners. March 18, 2017: Version 1.1 posted today contains a minor change to correct a grid sizing problem for the smallest possible square (3x3). Running/Exploring the ProgramSuggestions for Further Explorations

[Feedback] [Newsletters (subscribe/view)] [About me]Copyright © 20002017, Gary Darby All rights reserved. 