First, ask questions
The so-called "odd order magic square" refers to n is not less than 3 odd magic square. This kind of magic square is a variety of forms, here we only discuss one form of the normal magic square. For example: 3-order, 5-order, and 7-order magic Phalanx 3–4 are shown.
, ,
Figure 3–4 3 Order 5 order and 7 order magic Phalanx
It is easy to know that the Rubik's Cube constants of the three magic squares are 15, 65 and 175 respectively.
Now asked to give: can let the computer automatically output similar to figure 3–4 the n -order Odd magic square algorithm, where n is any given a number of not less than 3 odd.
second, simple analysis
The key to determining the odd-order magic Phalanx is to determine the numbers in its phalanx as required. Look at the three odd order magic matrices in Figure 3–4, it is not difficult to find:
1. Because it is a regular Rubik's Cube, it is filled with n 2 different integers in turn 1, 2, 3 、...、n 2;
2. The numbers on each row, column, and diagonal are different, but they are the same. This shows that the Rubik's cube constant can be obtained by the formula N ( n 2 + 1)/2.
3. The order of the numbers in the array does not follow the order of the rows and columns of the array cells, but the number "1" always appears in the middle of the first row of the array, and the number "N 2" is always in the middle of the array nth row, This indicates that the number arrangement in the array should have a certain regularity.
ImportJava.util.Scanner;/** * * @authorCold Blood **/ Public classJava_4 {Private int[] A; Private intJ, I, sum = 1; Private intN,n; PublicJava_4 (intN) {N=N; This. N =N; N=n-1; A=New int[N][n]; } Public voidJisuan () {i= 0; J=n/2; A[I][J]=sum; while(sum<=n*N) { if(i==0&&j!=N) {i=N; J++; Sum++; A[I][J]=sum; } if(sum==n*N) Break; if(j==n&&i!=0) {J=0; I--; Sum++; A[I][J]=sum; } if(j==n&&i==0) {i++; Sum++; A[I][J]=sum; } if(sum==n*N) Break; if(i!=0&&j!=n&&a[i-1][j+1]==0) {i--;j++;sum++; A[I][J]=sum; } if(sum==n*N) Break; if(i!=0&&j<n&&a[i-1][j+1]!=0) {i++;sum++; A[I][J]=sum; } if(sum==n*N) Break; } if(i==0&&j==0) {i=n;sum++;j++; A[I][J]=sum; } } Public voidpaint () { for(intK = 0;k<a.length;k++){ for(intL = 0;l<a.length;l++) {System.out.printf ("%-5D", A[k][l]); } System.out.println (); System.out.println (); } } Public Static voidMain (string[] args) {intM=0; @SuppressWarnings ("Resource") Scanner Nuber=NewScanner (system.in); M=Nuber.nextint (); Java_4 Java=NewJava_4 (m); Java.jisuan (); Java.paint (); }}
Java computes odd order magic matrices