Magic Square of Odd Order
Last Updated :
04 May, 2025
Given a positive integer n, your task is to generate a magic square of order n * n. A magic square of order n is an n * n grid filled with the numbers 1 through n² so that every row, every column, and both main diagonals each add up to the same total, called the magic constant (or magic sum) M. Because it uses each integer from 1 to n² exactly once, the value of M depends only on n, and has the value
M = n (n ^ 2 + 1) / 2
How does this formula work?
Sum of all numbers is 1 + 2 + 3, ... n^2 which is equal to n^2 * (n^2 + 1)/2 [We have simply applied natural number sum formula for n = n^2]. Now a magic square contains n divisions of sum M, so we can write n x M = n^2 * (n^2 + 1)/2. From this expression, we can derive, M = n * (n^2 + 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 |
| 4 | 4(4^2 + 1) / 2 = 34 |
| 5 | 5(5^2 + 1) / 2 = 65 |
| 6 | 6(6^2 + 1) / 2 = 111 |
Examples:
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: The below given approaches work only for odd value of n.
[Expected Approach - 1] - O(n ^ 2) Time and O(n ^ 2) 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 <bits/stdc++.h>
using namespace std;
// A function to generate odd sized magic squares
vector<vector<int>> generateSquare(int n) {
// initialize magic square
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
// A function to generate odd sized magic squares
import java.util.Arrays;
public class MagicSquare {
public static int[][] generateSquare(int n) {
// initialize magic square
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
# A function to generate odd sized magic squares
def generate_square(n):
# initialize magic square
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
n = 5
magic_square = generate_square(n)
for row in magic_square:
print(" ".join(map(str, row)))
C#
// A function to generate odd sized magic squares
using System;
using System.Linq;
class MagicSquare {
public static int[,] GenerateSquare(int n) {
// initialize magic square
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
// A function to generate odd sized magic squares
function generateSquare(n) {
// initialize magic square
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;
}
let n = 5;
let magicSquare = generateSquare(n);
for (let i = 0; i < n; i++) {
console.log(magicSquare[i].join(' '));
}
Output9 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(n ^ 2) Time and O(n ^ 2) 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 <bits/stdc++.h>
using namespace std;
// A function to generate odd sized magic squares
vector<vector<int>> generateSquare(int n) {
// initialize magic square
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
# A function to generate odd sized magic squares
def generateSquare(n):
# initialize magic square
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 {
// A function to generate odd sized magic squares
static List<List<int>> generateSquare(int n) {
// initialize magic square
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
// A function to generate odd sized magic squares
function generateSquare(n) {
// initialize magic square
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;
}
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());
}
Output9 3 22 16 15
2 21 20 14 8
25 19 13 7 1
18 12 6 5 24
11 10 4 23 17
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem