Magic Square of Odd Order

Last Updated : 26 Mar, 2026

Given a positive odd integer n, generate a magic square of order n × n. A magic square is an n × n grid filled with the numbers from 1 to n² such that the sum of every row, every column, and both main diagonals is equal. This common sum is called the magic constant (M).

It is guaranteed that for every positive odd integer n, a magic square can always be constructed.

Example:

Input: n = 3
Output: [ [2, 7, 6],
[9, 5, 1],
[4, 3, 8] ]
Explanation: Sum in each row, each column and both main diagonal is equal (15) and the matrix contains unique values from 1 to 9.

Input: n = 5
Output: [ [9, 3, 22, 16, 15],
[2, 21, 20, 14, 8],
[25, 19, 13, 7, 1],
[18, 12, 6, 5, 24],
[11, 10, 4, 23, 17] ]
Explanation: Sum in each row, each column and both main diagonal is equal (65) and the matrix contains unique values from 1 to 25.

Note: Sum of all numbers in any magic square (both even and odd order) is 1 + 2 + 3, ... n2 which is equal to n2 × (n2 + 1)/2 [We have simply applied natural number sum formula for n = n2]. Now a magic square contains n divisions of sum M where M is row or column or diagonal sum, so we can write n x M = n2 × (n2 + 1)/2. From this expression, we can derive, M = n × (n2 + 1)/2 .

For the first few “normal” magic squares (i.e. using 1…n²), the magic constants are :

Order (n)Magic Constant (M)
3

3(3^2 + 1) / 2 = 15

5

5(5^2 + 1) / 2 = 65

7

7(7^2 + 1) / 2 = 175

Note: The below given approaches work only for odd value of n.

[Expected Approach - 1] - O(n2) Time and O(n2) Space

Let us take a look at first few magic squares to find a pattern for filling numbers.

Magic Square of size 3
2 7 6
9 5 1
4 3 8

Magic Square of size 5
9 3 22 16 15
2 21 20 14 8
25 19 13 7 1
18 12 6 5 24
11 10 4 23 17]

Magic Square of size 7
20 12 4 45 37 29 28
11 3 44 36 35 27 19
2 43 42 34 26 18 10
49 41 33 25 17 9 1
40 32 24 16 8 7 48
31 23 15 14 6 47 39
22 21 13 5 46 38 30

Did you find any pattern in which the numbers are stored? 

  • In any magic square, the first number i.e. 1 is stored at position (n/2, n-1). Let this position be (i, j). The next number is stored at position (i-1, j+1) where we can consider each row & column as circular array i.e. they wrap around.
  • At any time, if the calculated row position becomes -1, it will wrap around to n-1. Similarly, if the calculated column position becomes n, it will wrap around to 0.
  • If the magic square already contains a number at the calculated position, calculated column position will be decremented by 2, and calculated row position will be incremented by 1.
  • If the calculated row position is -1 & calculated column position is n, the new position would be: (0, n-2). 

The idea is to place each integer from 1 up to n² one at a time, always moving up one row and right one column from the last placement—wrapping around the edges as if rows and columns were circular—and applying two special corrections when that move lands outside the square on both axes or on an already‑filled cell.

Follow the below given steps:

  • Create an n × n grid mat initialized to zeros, and set your starting position to row i = n/2, column j = n − 1.
  • Repeat for each num from 1 through n²:
    • Compute the candidate position by decrementing i by 1 and incrementing j by 1.
    • If that move sends you both above the top (i < 0) and beyond the right edge (j == n), reset to i = 0, j = n − 2.
    • Otherwise, if only one coordinate is out of range, wrap it around: any i < 0 becomes n − 1, any j == n becomes 0.
    • If mat[i][j] is already nonzero, backtrack two columns (subtract 2 from j) and move down one row (add 1 to i), and retry placing the same num.
    • Otherwise, store num in mat[i][j], then proceed to the next number by again decrementing i and incrementing j.
  • Once all numbers are placed without conflict, mat is your completed magic square.
C++
#include <iostream>
#include<vector>
using namespace std;

vector<vector<int>> generateSquare(int n) {

    vector<vector<int>> mat(n, vector<int>(n, 0)); 

    // Initialize position for 1
    int i = n / 2;
    int j = n - 1;

    // One by one put all values in magic square
    for (int num = 1; num <= n * n;) {

        // if row is -1 and column becomes n, 
        // set row = 0, col = n -2
        if (i == -1 && j == n)  {
            j = n - 2;
            i = 0;
        }
        else {

            // If next number goes to out of 
            // square's right side
            if (j == n)
                j = 0;

            // If next number goes to out of
            // square's upper side
            if (i < 0)
                i = n - 1;
        }

        // If number is already present decrement 
        // column by 2, and increment row by 1
        if (mat[i][j]) {
            j -= 2;
            i++;
            continue;
        }
        else {

            // set number
            mat[i][j] = num++; 
        }

        // increment and decrement
        // column and row by 1 respectively
        j++;
        i--; 
    }

    return mat;
}

int main() {
    int n = 5;
    vector<vector<int>> magicSquare = generateSquare(n);
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
            cout << magicSquare[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}
Java
import java.util.Arrays;

public class GfG {
    public static int[][] generateSquare(int n) {

        int[][] mat = new int[n][n];

        // Initialize position for 1
        int i = n / 2;
        int j = n - 1;

        // One by one put all values in magic square
        for (int num = 1; num <= n * n;) {
            // if row is -1 and column becomes n,
            // set row = 0, col = n -2
            if (i == -1 && j == n) {
                j = n - 2;
                i = 0;
            } else {
                // If next number goes to out of
                // square's right side
                if (j == n)
                    j = 0;

                // If next number goes to out of
                // square's upper side
                if (i < 0)
                    i = n - 1;
            }

            // If number is already present decrement
            // column by 2, and increment row by 1
            if (mat[i][j] != 0) {
                j -= 2;
                i++;
                continue;
            } else {
                // set number
                mat[i][j] = num++;
            }

            // increment and decrement
            // column and row by 1 respectively
            j++;
            i--;
        }

        return mat;
    }

    public static void main(String[] args) {
        int n = 5;
        int[][] magicSquare = generateSquare(n);
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(magicSquare[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Python
def generate_square(n):

    mat = [[0] * n for _ in range(n)]

    # Initialize position for 1
    i = n // 2
    j = n - 1

    # One by one put all values in magic square
    for num in range(1, n * n + 1):
        # if row is -1 and column becomes n,
        # set row = 0, col = n -2
        if i == -1 and j == n:
            j = n - 2
            i = 0
        else:
            # If next number goes to out of
            # square's right side
            if j == n:
                j = 0

            # If next number goes to out of
            # square's upper side
            if i < 0:
                i = n - 1

        # If number is already present decrement
        # column by 2, and increment row by 1
        if mat[i][j]:
            j -= 2
            i += 1
            continue
        else:
            # set number
            mat[i][j] = num

        # increment and decrement
        # column and row by 1 respectively
        j += 1
        i -= 1

    return mat

if __name__=="__main__":
    n = 5
    magic_square = generate_square(n)
    for row in magic_square:
        print(" ".join(map(str, row)))
C#
using System;
using System.Linq;

class GfG {
    public static int[,] GenerateSquare(int n) {
 
        int[,] mat = new int[n, n];

        // Initialize position for 1
        int i = n / 2;
        int j = n - 1;

        // One by one put all values in magic square
        for (int num = 1; num <= n * n;) {
            // if row is -1 and column becomes n,
            // set row = 0, col = n -2
            if (i == -1 && j == n) {
                j = n - 2;
                i = 0;
            } else {
                // If next number goes to out of
                // square's right side
                if (j == n)
                    j = 0;

                // If next number goes to out of
                // square's upper side
                if (i < 0)
                    i = n - 1;
            }

            // If number is already present decrement
            // column by 2, and increment row by 1
            if (mat[i, j] != 0) {
                j -= 2;
                i++;
                continue;
            } else {
                // set number
                mat[i, j] = num++;
            }

            // increment and decrement
            // column and row by 1 respectively
            j++;
            i--;
        }

        return mat;
    }

    public static void Main() {
        int n = 5;
        int[,] magicSquare = GenerateSquare(n);
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                Console.Write(magicSquare[i, j] + " ");
            }
            Console.WriteLine();
        }
    }
}
JavaScript
function generateSquare(n) {

    let mat = Array.from({ length: n }, () => Array(n).fill(0));

    // Initialize position for 1
    let i = Math.floor(n / 2);
    let j = n - 1;

    // One by one put all values in magic square
    for (let num = 1; num <= n * n;) {
        // if row is -1 and column becomes n,
        // set row = 0, col = n -2
        if (i === -1 && j === n) {
            j = n - 2;
            i = 0;
        } else {
            // If next number goes to out of
            // square's right side
            if (j === n)
                j = 0;

            // If next number goes to out of
            // square's upper side
            if (i < 0)
                i = n - 1;
        }

        // If number is already present decrement
        // column by 2, and increment row by 1
        if (mat[i][j]) {
            j -= 2;
            i++;
            continue;
        } else {
            // set number
            mat[i][j] = num++;
        }

        // increment and decrement
        // column and row by 1 respectively
        j++;
        i--;
    }

    return mat;
}

//Driver code
let n = 5;
let magicSquare = generateSquare(n);
for (let i = 0; i < n; i++) {
    console.log(magicSquare[i].join(' '));
}

Output
9 3 22 16 15 
2 21 20 14 8 
25 19 13 7 1 
18 12 6 5 24 
11 10 4 23 17 

[Expected Approach - 2] - Using Modulo Arithmetic - O(n2) Time and O(n2) Space

The idea is to treat he grid as if its rows and columns wrap around (using modulo arithmetic), placing each integer in sequence by moving one step up and one step right—except whenever you’ve just placed a multiple of n, you instead move one step left. This simple cyclic movement ensures every row, column, and diagonal sums to the same magic constant.

Follow the below given steps:

  • Create an empty n×n grid mat and set your starting coordinates to row i = n/2 and column j = n – 1.
  • Place the first number (1) at (i, j).
  • For each next num from 2 up to n²:
    • If the previous number was a multiple of n, move one column left; otherwise, move one row up and one column right.
    • After adjusting i or j, add n and then take each coordinate modulo n to wrap around the grid.
    • Place num at the resulting (i, j).
  • Continue until all numbers 1 through n² have been placed; the wrapping guarantees the magic‑square property.

Below is given the implementation:

C++
#include <iostream>
#include<vector>
using namespace std;

vector<vector<int>> generateSquare(int n) {

    vector<vector<int>> mat(n, vector<int>(n, 0)); 

    // Initialize position for 1
    int i = n / 2;
    int j = n - 1;

    // One by one put all values in magic square
    for (int num = 1; num <= n * n; num++) {

        // put the current element at (i, j)
        mat[i][j] = num;

        // if we get multiple of n, move left
        if(num % n == 0) {
            j--;
        }

        // else move to top-right
        else {
            i--; j++;
        }
        
        // add n and take modulo 
        // to avoid out of bounds
        i += n; i %= n;
        j += n; j %= n;
    }
    return mat;
}

int main() {
    int n = 5;
    vector<vector<int>> magicSquare = generateSquare(n);
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
            cout << magicSquare[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}
Java
import java.util.*;

class GfG {

    // A function to generate odd sized magic squares
    static List<List<Integer>> generateSquare(int n) {

        // initialize magic square
        List<List<Integer>> mat = new ArrayList<>();
        for (int ii = 0; ii < n; ii++) {
            mat.add(new ArrayList<>(Collections.nCopies(n, 0)));
        }

        // Initialize position for 1
        int i = n / 2;
        int j = n - 1;

        // One by one put all values in magic square
        for (int num = 1; num <= n * n; num++) {

            // put the current element at (i, j)
            mat.get(i).set(j, num);

            // if we get multiple of n, move left
            if (num % n == 0) {
                j--;
            }

            // else move to top-right
            else {
                i--; j++;
            }

            // add n and take modulo 
            // to avoid out of bounds
            i += n; i %= n;
            j += n; j %= n;
        }

        return mat;
    }

    public static void main(String[] args) {
        int n = 5;
        List<List<Integer>> magicSquare = generateSquare(n);
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(magicSquare.get(i).get(j) + " ");
            }
            System.out.println();
        }
    }
}
Python
def generateSquare(n):

    mat = [[0 for _ in range(n)] for _ in range(n)]

    # Initialize position for 1
    i = n // 2
    j = n - 1

    # One by one put all values in magic square
    for num in range(1, n * n + 1):

        # put the current element at (i, j)
        mat[i][j] = num

        # if we get multiple of n, move left
        if num % n == 0:
            j -= 1

        # else move to top-right
        else:
            i -= 1
            j += 1

        # add n and take modulo 
        # to avoid out of bounds
        i = (i + n) % n
        j = (j + n) % n

    return mat

if __name__ == "__main__":
    n = 5
    magicSquare = generateSquare(n)
    for i in range(n):
        for j in range(n):
            print(magicSquare[i][j], end=" ")
        print()
C#
using System;
using System.Collections.Generic;

class GfG {

    static List<List<int>> generateSquare(int n) {

        List<List<int>> mat = new List<List<int>>();
        for (int ii = 0; ii < n; ii++) {
            mat.Add(new List<int>());
            for (int jj = 0; jj < n; jj++)
                mat[ii].Add(0);
        }

        // Initialize position for 1
        int i = n / 2;
        int j = n - 1;

        // One by one put all values in magic square
        for (int num = 1; num <= n * n; num++) {

            // put the current element at (i, j)
            mat[i][j] = num;

            // if we get multiple of n, move left
            if (num % n == 0) {
                j--;
            }

            // else move to top-right
            else {
                i--; j++;
            }

            // add n and take modulo 
            // to avoid out of bounds
            i += n; i %= n;
            j += n; j %= n;
        }

        return mat;
    }

    static void Main() {
        int n = 5;
        List<List<int>> magicSquare = generateSquare(n);
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                Console.Write(magicSquare[i][j] + " ");
            }
            Console.WriteLine();
        }
    }
}
JavaScript
function generateSquare(n) {

    let mat = [];
    for (let ii = 0; ii < n; ii++) {
        mat[ii] = [];
        for (let jj = 0; jj < n; jj++)
            mat[ii][jj] = 0;
    }

    // Initialize position for 1
    let i = Math.floor(n / 2);
    let j = n - 1;

    // One by one put all values in magic square
    for (let num = 1; num <= n * n; num++) {

        // put the current element at (i, j)
        mat[i][j] = num;

        // if we get multiple of n, move left
        if (num % n === 0) {
            j--;
        }

        // else move to top-right
        else {
            i--; j++;
        }

        // add n and take modulo 
        // to avoid out of bounds
        i += n; i %= n;
        j += n; j %= n;
    }

    return mat;
}

// Driver code
let n = 5;
let magicSquare = generateSquare(n);
for (let i = 0; i < n; i++) {
    let row = "";
    for (let j = 0; j < n; j++) {
        row += magicSquare[i][j] + " ";
    }
    console.log(row.trim());
}

Output
9 3 22 16 15 
2 21 20 14 8 
25 19 13 7 1 
18 12 6 5 24 
11 10 4 23 17 
Comment