Java implementation of odd order magic square construction

Source: Internet
Author: User

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

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.