First, the design flowchart is as follows
Second, the Java language code implementation
PackageMagicsquare;//the realization of odd magic square Public classmagic_odd {//N is the order of the magic square Public Static int[] Magicodd (intN) {//construct a square of (n+2) * (n+2) Order int[] Square =New int[n + 1] [n + 1]; inti = 0; intJ = (n + 1)/2; //from the middle of the first line the number (is 1) to begin to fill the magic square//N-Order magic squares have a total of n*n numbers (from 1~n*n)//an algorithm for realizing odd-order magic squares for(intkey = 1; Key <= n * N; key++) { if((key% n) = = 1) I++; Else{//fill the top right corner of the current numberi--; J++; } if(i = = 0) {//Judging Condition: If the first line of the (n+2) * (n+2) square matrix if(j==n+1) {i=2; J=N; }Else{i=N; } } Else{ if(j==n+1) {J=1; }} Square[i][j]=key; } //The square of the (n+2) * (n+2) Order is screened for the middle N*n order magic square . int[] Matrix =New int[N][n]; for(intk = 0; K < Matrix.length; k++) { for(intL = 0; L < Matrix[0].length; l++) {Matrix[k][l]= square[k + 1][l + 1]; } } returnMatrix; } //test function Public Static voidMain (string[] args) {int[] Magic = magic_odd.magicodd (11);//Test 11 Order Magic Square for(intk = 0; K < Magic.length; k++) { for(intL = 0; L < Magic[0].length; l++) {System.out.print (Magic[k][l]+ " "); } System.out.println (); } }}
Third, the test results:
(See the relevant source code resources: https://github.com/shenxiaolinZERO/Resources/tree/master/Resources/Magic_Test)
Java implementation of odd order magic square construction