Excel – How to build magic square with VBA, following Python Mod Mathematics

Some 4 years ago I wrote an article for calculating magic square with python. What the article did was actually checking whether the square is magic, and not calculating a new one. This one is going to show how these squares are built.

Wikipedia says that magic square is a square grid, filled with distinct positive integers in range 1,2, 3... n^2, such that each cell contains a different integer and the sum of the integers per column, row and diagonals is equal. In the general case, building a magic square in VBA requires a few more checks, but as I have recently got a bit deeper into Python, I have noticed that Python has its own way of mathematics, when it comes to negative numbers. (Modulo Operation on Negative Numbers). Long story short, Python claims that:

while in the VBA (and all the C languages), -1 mod 3 and 1 mod 3 would return -1 or 1 . Nothing to do with 2. Which mathematics is “better” is another story, the thing is that the “Python way of doing maths” allows us to write a magic square in quite quick way. If we want to represent the Python mod function in VBA, this is it:

With this function in hand, building a Magic Square in VBA becomes “a piece of cake”:

With a size big enough to see what is going on, one may notice the logic – build always up and to the left except for the case when the Array((i-1) mod size, (j+1) mod size) is taken:

This is the whole code, allowing you to impress someone. Start with the Main() function and feel free to change the size:

The same code in Python, without the “fancy” excel visualisation looks like this:

Still, the formatting is not that bad:


Tagged with: , , ,