Optimizing magic_square code