N (odd) Order magic square-java implementation code

Source: Internet
Author: User

After reading the strongest brain, there is a period of N-order magic cube, as a programmer, my first reaction when I can use the program implementation, here to publish the N (odd) Order magic square Java implementation code:

Package Com.lzugis.test;public class Practice {public static int[][] Magicodd (int n) {int[][] square = new Int[n + 1][n + 1];int i = 0;int J = (n + 1)/2;for (int key = 1; key <= n * N; key++) {if ((key% n) = = 1) i++;else {i--;j++;} if (i = = 0) i = n;if (J > N) j = 1;square[i][j] = key;} int[][] Matrix = new Int[n][n];for (int k = 0; k < matrix.length; k++) {for (int l = 0; l < matrix[0].length; l++) { Matrix[k][l] = square[k + 1][l + 1];}} return matrix;} public static void Main (string[] args) {int[][] Magic = practice.magicodd (3), for (int k = 0; k < magic.length; k++) {fo R (int l = 0; l < magic[0].length; l++) {System.out.print (Magic[k][l] + "");} System.out.println ();}}}
The effect is as follows:


3 Order Magic Square


5 Order Magic Square

Note:

Magic Square is a method of arranging numbers in a square lattice so that the numbers on each row, column, and diagonal are equal. The value of the magic square Middle lattice is (n*n+1)/2, that is, the 3-order magic Square is (3*3+1)/2=5, the3-order magic Square is (5*5+1)/2=13, ...

If you have any questions, please contact:

qq:1004740957

Email:[email protected]

N (odd) Order magic square-java implementation code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.