C ++ classic magic square algorithm problem -4N

50.Algorithm Gossip: 4N magic square

Explanation

Odd magic square with the same, wherein each row seeking, each column and each diagonal are equal, and this square dimension is a multiple of four.

solution

Let's look at the 4X4 matrix solution:
Here Insert Picture Description
simply put, is a left-over from the 1 start in sequence to fill, but not in case of diagonal fill, the other from the start to fill the upper left of 16, but Consignee in diagonal, then the two together is answered; if N is greater than 2, the unit places 4X4 diagonal Videos:
Here Insert Picture Description
as to how the determination of the position of the diagonal line, there are two formulas, may be interested to see confirmed drawing, as follows FIG: top left to bottom right:

j % 4 == i % 4
右上至左下:(j % 4 + i % 4) == 1

The sample code

#include<stdio.h> 
#include<stdlib.h>
#define N 8

    int main(void) {
        int i, j;
        int square[ N + 1][N + 1] ={
            0
        } ;

        for (j = 1; j <= N; j++) {
            for (i = 1; i <= N; i++) {
                if (j % 4 == i % 4 || (j % 4 + i % 4) == 1) square[i][j] = (N + 1 - i) * N - j + 1;

                else

            }
        }


        square[i][j] = (i - 1) * N + j;


        for (i = 1; i <= N; i++) {
            for (j = 1; j <= N; j++)
                printf("%2d ", square[i][j]);
            printf("\n");
        }


        return 0;
    }

Released 1165 original articles · won praise 928 · views 70000 +

Guess you like

Origin blog.csdn.net/weixin_42528266/article/details/104022431