Given an integer n and an n × n matrix mat[][]. Fill the matrix with distinct integers from 1 to n² such that the sum of every row, every column, and both main diagonals are equal. If it is possible to construct such a matrix, fill mat[][] with any valid arrangement. Otherwise, fill every cell of mat[][] with -1.
Note: In the practice problem, the driver code will verify the filled matrix and print true if:
It forms a valid magic square using all integers from 1 to n² exactly once, or
Every element of the matrix is -1 when no magic square exists.
Otherwise, it will print false.
Example:
Input: n = 3 Output: true Explanation: A valid matrix exists:
where each row ([2, 7, 6], [9, 5, 1], [4, 3, 8]), each column ([2, 9, 4], [7, 5, 3], [6, 1, 8]) and both diagonals ([2, 5, 8], [6, 5, 4]) all have sum equal to 15.
Input: n = 2 Output: [[-1, -1], [-1, -1]] Explanation: No valid magic square possible for n = 2.
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 :
[Naive Approach] Magic Square Construction Using Backtracking – O((n²)!) Time and O(n²) Space
Instead of generating all permutations, we fill the matrix cell by cell and maintain running sums for rows, columns, and diagonals. At each step, we check whether the current configuration can still lead to a valid solution. If any constraint is violated, we backtrack immediately, which helps in pruning invalid states early and improves efficiency.
Compute k = n2 and magic sum S = k(k+1)/2n
Initialize row, column, diagonal sums, and visited array
Start filling matrix from (0, 0) in row-wise order
For each cell, try all unused numbers from 1 to n²
Place number and update row/column/diagonal sums
Check constraints only when row/column/diagonal is completed
If valid, move to next cell recursively, else undo changes (backtrack)
Continue until all cells are filled or all options fail
C++
#include<bits/stdc++.h>usingnamespacestd;// r[i] -> sum of row i// c[j] -> sum of column j// d[0] -> main diagonal sum// d[1] -> anti-diagonal sum// vis[val] -> whether number val is already usedintr[25],c[25],d[2],vis[205],s,k;boolsolve(inti,intj,intn,vector<vector<int>>&mat){// Base case: if all rows are filled, solution is foundif(i==n)returntrue;// Move to next cell in row-wise orderintni=(j==n-1)?i+1:i;intnj=(j==n-1)?0:j+1;// Try all values from 1 to n*nfor(intval=1;val<=k;val++){// If value is not used yetif(!vis[val]){// Place value in matrixmat[i][j]=val;vis[val]=1;// Update row and column sumsr[i]+=val;c[j]+=val;// Update diagonal sums if neededif(i==j)d[0]+=val;if(i+j==n-1)d[1]+=val;// Pruning condition:boolbad=false;if(j==n-1&&r[i]!=s)bad=true;if(i==n-1&&c[j]!=s)bad=true;if(i==n-1&&j==n-1&&d[0]!=s)bad=true;if(i==n-1&&j==0&&d[1]!=s)bad=true;// If valid so far, continue recursionif(!bad&&solve(ni,nj,n,mat))returntrue;// Backtracking step: undo changesvis[val]=0;r[i]-=val;c[j]-=val;if(i==j)d[0]-=val;if(i+j==n-1)d[1]-=val;mat[i][j]=0;}}returnfalse;}voidfillMagicSquare(intn,vector<vector<int>>&mat){// Initialize matrix with 0mat.assign(n,vector<int>(n,0));// Special case: no magic square possible for n = 2if(n==2){for(inti=0;i<n;i++)for(intj=0;j<n;j++)mat[i][j]=-1;return;}// Total numbers from 1 to n*nk=n*n;// Magic constant (sum of each row/column/diagonal)s=(k*(k+1))/2/n;// Initialize helper arraysmemset(r,0,sizeof(r));memset(c,0,sizeof(c));memset(d,0,sizeof(d));memset(vis,0,sizeof(vis));// Start backtracking from first cellsolve(0,0,n,mat);// If solution not fully filled, mark invalid cells as -1for(inti=0;i<n;i++){for(intj=0;j<n;j++){if(mat[i][j]==0)mat[i][j]=-1;}}}intmain(){intn=3;vector<vector<int>>mat;fillMagicSquare(n,mat);for(auto&row:mat){for(autox:row)cout<<x<<" ";cout<<endl;}}
Java
importjava.util.Arrays;classGFG{// r[i] -> sum of row i// c[j] -> sum of column j// d[0] -> main diagonal sum// d[1] -> anti-diagonal sum// vis[val] -> whether number val is already usedstaticint[]r=newint[25];staticint[]c=newint[25];staticint[]d=newint[2];staticint[]vis=newint[205];staticints,k;staticbooleansolve(inti,intj,intn,int[][]mat){// Base case: if all rows are filled, solution is foundif(i==n)returntrue;// Move to next cell in row-wise orderintni=(j==n-1)?i+1:i;intnj=(j==n-1)?0:j+1;// Try all values from 1 to n*nfor(intval=1;val<=k;val++){// If value is not used yetif(vis[val]==0){// Place value in matrixmat[i][j]=val;vis[val]=1;// Update row and column sumsr[i]+=val;c[j]+=val;// Update diagonal sums if neededif(i==j)d[0]+=val;if(i+j==n-1)d[1]+=val;// Pruning conditionbooleanbad=false;if(j==n-1&&r[i]!=s)bad=true;if(i==n-1&&c[j]!=s)bad=true;if(i==n-1&&j==n-1&&d[0]!=s)bad=true;if(i==n-1&&j==0&&d[1]!=s)bad=true;if(!bad&&solve(ni,nj,n,mat))returntrue;// Backtrackingvis[val]=0;r[i]-=val;c[j]-=val;if(i==j)d[0]-=val;if(i+j==n-1)d[1]-=val;mat[i][j]=0;}}returnfalse;}staticvoidfillMagicSquare(intn,int[][]mat){// Initialize matrix with 0for(int[]row:mat)Arrays.fill(row,0);// Special case: n = 2 not possibleif(n==2){for(inti=0;i<n;i++)Arrays.fill(mat[i],-1);return;}k=n*n;s=(k*(k+1))/2/n;Arrays.fill(r,0);Arrays.fill(c,0);Arrays.fill(d,0);Arrays.fill(vis,0);solve(0,0,n,mat);// If not filled properly → mark -1for(inti=0;i<n;i++){for(intj=0;j<n;j++){if(mat[i][j]==0)mat[i][j]=-1;}}}publicstaticvoidmain(String[]args){intn=3;int[][]mat=newint[n][n];fillMagicSquare(n,mat);for(inti=0;i<n;i++){for(intj=0;j<n;j++)System.out.print(mat[i][j]+" ");System.out.println();}}}
Python
# r[i] -> sum of row i# c[j] -> sum of column j# d[0] -> main diagonal sum# d[1] -> anti-diagonal sum# vis[val] -> whether number val is already usedr=[0]*25c=[0]*25d=[0]*2vis=[0]*205s=0k=0defsolve(i,j,n,mat):# Base case: if all rows are filled, solution is foundifi==n:returnTrue# Move to next cell in row-wise orderni=(i+1)if(j==n-1)elseinj=0if(j==n-1)elsej+1# Try all values from 1 to n*nforvalinrange(1,k+1):# If value is not used yetifvis[val]==0:# Place value in matrixmat[i][j]=valvis[val]=1# Update row and column sumsr[i]+=valc[j]+=val# Update diagonal sums if neededifi==j:d[0]+=valifi+j==n-1:d[1]+=val# Pruning condition:# Only check constraints when row/col/diagonal is completebad=Falseifj==n-1andr[i]!=s:bad=Trueifi==n-1andc[j]!=s:bad=Trueifi==n-1andj==n-1andd[0]!=s:bad=Trueifi==n-1andj==0andd[1]!=s:bad=True# If valid so far, continue recursionifnotbadandsolve(ni,nj,n,mat):returnTrue# Backtracking step: undo changesvis[val]=0r[i]-=valc[j]-=valifi==j:d[0]-=valifi+j==n-1:d[1]-=valmat[i][j]=0returnFalsedeffillMagicSquare(n,mat):globals,k# Initialize matrix with 0foriinrange(n):forjinrange(n):mat[i][j]=0# Special case: no magic square possible for n = 2ifn==2:foriinrange(n):forjinrange(n):mat[i][j]=-1return# Total numbers from 1 to n*nk=n*n# Magic constant (sum of each row/column/diagonal)s=(k*(k+1))//2//n# Initialize helper arraysforiinrange(205):vis[i]=0foriinrange(25):r[i]=0c[i]=0d[0]=d[1]=0# Start backtracking from first cellsolve(0,0,n,mat)if__name__=="__main__":n=3mat=[[0for_inrange(n)]for_inrange(n)]fillMagicSquare(n,mat)forrowinmat:print(*row)
C#
usingSystem;classSolution{// r[i] -> sum of row i// c[j] -> sum of column j// d[0] -> main diagonal sum// d[1] -> anti-diagonal sum// vis[val] -> whether number val is already usedstaticint[]r=newint[25];staticint[]c=newint[25];staticint[]d=newint[2];staticint[]vis=newint[205];staticints,k;staticboolsolve(inti,intj,intn,int[,]mat){// Base case: if all rows are filled, solution is foundif(i==n)returntrue;// Move to next cell in row-wise orderintni=(j==n-1)?i+1:i;intnj=(j==n-1)?0:j+1;// Try all values from 1 to n*nfor(intval=1;val<=k;val++){// If value is not used yetif(vis[val]==0){// Place value in matrixmat[i,j]=val;vis[val]=1;// Update row and column sumsr[i]+=val;c[j]+=val;// Update diagonal sums if neededif(i==j)d[0]+=val;if(i+j==n-1)d[1]+=val;// Pruning condition:boolbad=false;if(j==n-1&&r[i]!=s)bad=true;if(i==n-1&&c[j]!=s)bad=true;if(i==n-1&&j==n-1&&d[0]!=s)bad=true;if(i==n-1&&j==0&&d[1]!=s)bad=true;// If valid so far, continue recursionif(!bad&&solve(ni,nj,n,mat))returntrue;// Backtracking step: undo changesvis[val]=0;r[i]-=val;c[j]-=val;if(i==j)d[0]-=val;if(i+j==n-1)d[1]-=val;mat[i,j]=0;}}returnfalse;}publicstaticvoidfillMagicSquare(intn,int[,]mat){// Initialize matrix with 0for(inti=0;i<n;i++)for(intj=0;j<n;j++)mat[i,j]=0;// Special case: no magic square possible for n = 2if(n==2){for(inti=0;i<n;i++)for(intj=0;j<n;j++)mat[i,j]=-1;return;}// Total numbers from 1 to n*nk=n*n;// Magic constant (sum of each row/column/diagonal)s=(k*(k+1))/2/n;// Initialize helper arraysArray.Clear(r,0,r.Length);Array.Clear(c,0,c.Length);Array.Clear(d,0,d.Length);Array.Clear(vis,0,vis.Length);// Start backtracking from first cellsolve(0,0,n,mat);// If solution not fully filled, mark invalid cells as -1for(inti=0;i<n;i++){for(intj=0;j<n;j++){if(mat[i,j]==0)mat[i,j]=-1;}}}publicstaticvoidMain(){intn=3;int[,]mat=newint[n,n];fillMagicSquare(n,mat);for(inti=0;i<n;i++){for(intj=0;j<n;j++)Console.Write(mat[i,j]+" ");Console.WriteLine();}}}
JavaScript
// r[i] -> sum of row i// c[j] -> sum of column j// d[0] -> main diagonal sum// d[1] -> anti-diagonal sum// vis[val] -> whether number val is already usedletr=newArray(25).fill(0);letc=newArray(25).fill(0);letd=newArray(2).fill(0);letvis=newArray(205).fill(0);lets=0,k=0;functionsolve(i,j,n,mat){// Base case: if all rows are filled, solution is foundif(i==n)returntrue;// Move to next cell in row-wise orderletni=(j==n-1)?i+1:i;letnj=(j==n-1)?0:j+1;// Try all values from 1 to n*nfor(letval=1;val<=k;val++){// If value is not used yetif(vis[val]==0){// Place value in matrixmat[i][j]=val;vis[val]=1;// Update row and column sumsr[i]+=val;c[j]+=val;// Update diagonal sums if neededif(i==j)d[0]+=val;if(i+j==n-1)d[1]+=val;// Pruning condition:// Only check constraints when row/col/diagonal is completeletbad=false;if(j==n-1&&r[i]!=s)bad=true;if(i==n-1&&c[j]!=s)bad=true;if(i==n-1&&j==n-1&&d[0]!=s)bad=true;if(i==n-1&&j==0&&d[1]!=s)bad=true;// If valid so far, continue recursionif(!bad&&solve(ni,nj,n,mat))returntrue;// Backtracking step: undo changesvis[val]=0;r[i]-=val;c[j]-=val;if(i==j)d[0]-=val;if(i+j==n-1)d[1]-=val;mat[i][j]=0;}}returnfalse;}functionfillMagicSquare(n,mat){// Initialize matrix with 0for(leti=0;i<n;i++){for(letj=0;j<n;j++){mat[i][j]=0;}}// Special case: no magic square possible for n = 2if(n==2){for(leti=0;i<n;i++)for(letj=0;j<n;j++)mat[i][j]=-1;return;}// Total numbers from 1 to n*nk=n*n;// Magic constant (sum of each row/column/diagonal)s=Math.floor((k*(k+1))/2/n);// Initialize helper arraysr.fill(0);c.fill(0);d.fill(0);vis.fill(0);// Start backtracking from first cellsolve(0,0,n,mat);// If solution not fully filled, mark invalid cells as -1for(leti=0;i<n;i++){for(letj=0;j<n;j++){if(mat[i][j]==0)mat[i][j]=-1;}}}// Driver codeletn=3;letmat=Array.from({length:n},()=>Array(n).fill(0));fillMagicSquare(n,mat);for(leti=0;i<n;i++){console.log(mat[i].join(" "));}
Output
2 7 6
9 5 1
4 3 8
[Expected Approach] Magic Square Construction Based on Order of n - O(n²) Time and O(n²) Space
The construction technique for a magic square depends on the value of n. Based on the order of the square, magic squares are classified into three categories:
Case 1: Odd Order (Siamese Method)
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.
Let us take a look at first few magic squares to find a pattern for filling numbers.
Did you find any pattern in which the numbers are stored?
The first number 1 is placed at position (n / 2, n − 1). Let this position be (i, j).
The next number is placed at position (i − 1, j + 1).
The matrix is treated as a circular grid, so if i < 0, it wraps to n − 1, and if j == n, it wraps to 0.
If the calculated position is already filled, we move to a new position by setting i = i + 1 and j = j − 2, and then continue the process.
If both conditions occur together (i == −1 and j == n), the position is reset to (0, n − 2).
This process is repeated until all numbers from 1 to n² are placed in the matrix.
Case 2: Doubly Even (n % 4 == 0)
For a doubly even order magic square (n%4=0), the matrix is first filled sequentially with numbers from 1 to n^2. After filling the matrix, certain cells are replaced by their complements, where the complement of a value x is given by n2+1-x. The cells to be replaced follow a fixed pattern that repeats in every 4 × 4 block of the matrix.
For example, when n = 8.
Step 1: First, fill numbers from 1 to n² (1 to 64) in row-wise order:
Step 2: Since 8 is divisible by 4, we divide the matrix into four 4×4 blocks:
Each block follows the same pattern.
Step 3: In every 4 × 4 block, mark cells like this:
Step 4: For each x cell, replace value using: new Value = n² + 1 - old value
Step 5: Consider the first 4 × 4 block:
After replacing the cells marked by the pattern, it becomes:
For instance, 2 is replaced by 65-2 = 63, 3 by 65 - 3 = 62, and 12 by 65 - 12 = 53. Applying the same pattern to every 4 × 4 block of the matrix produces a valid doubly even magic square.
This works because every replaced value and its complement add up to the same constant (65 in this case), ensuring that all rows, columns, and diagonals have the same sum.
For n = 8, the magic sum is: n(n2+1)/2=8(64+1)/2 = 260. Thus, every row, every column, and both diagonals sum to 260, forming a valid magic square.
Case 3: Singly Even (n % 4 == 2)
For a singly even order magic square (n is divisible by 2 but not by 4), the construction is not direct. Instead, the matrix is built using a quadrant decomposition technique combined with the Siamese method on smaller odd-order squares.
Step 1: Divide the n x n matrix into four equal quadrants of size (n/2) x (n/2):
Step 2: Construct a magic square of size (n/2) using the Siamese method and fill all four quadrants with it. Each quadrant is filled with shifted values to cover the full range from 1 to n²:
A -> +0
B -> + (n² / 4)
C -> + 2(n² / 4)
D -> + 3(n² / 4)
This ensures all numbers are unique and lie between 1 and n². Example for n = 6 .
Step 3: After filling, the matrix is not yet a valid magic square. To balance row and column sums, a column swapping step is applied. Swap specific columns between:
Left part of A and C
Right part of B and D
This rearrangement fixes the structural imbalance caused by quadrant filling. After performing the swaps, the matrix becomes a valid magic square.
C++
#include<bits/stdc++.h>usingnamespacestd;// Case 1: Odd order magic square (Siamese method)vector<vector<int>>fillOddMagicSquare(intn){vector<vector<int>>mat(n,vector<int>(n,0));inti=n/2;intj=n-1;for(intnum=1;num<=n*n;){if(i==-1&&j==n){i=0;j=n-2;}else{if(j==n)j=0;if(i==-1)i=n-1;}if(mat[i][j]!=0){i++;j-=2;continue;}mat[i][j]=num++;i--;j++;}returnmat;}// Case 2: Doubly even (n % 4 == 0)vector<vector<int>>fillDoublyEvenMagicSquare(intn){vector<vector<int>>mat(n,vector<int>(n));for(inti=0;i<n;i++){for(intj=0;j<n;j++){mat[i][j]=i*n+j+1;}}for(inti=0;i<n;i++){for(intj=0;j<n;j++){if(((i%4==0||i%4==3)&&(j%4==1||j%4==2))||((i%4==1||i%4==2)&&(j%4==0||j%4==3))){mat[i][j]=n*n+1-mat[i][j];}}}returnmat;}// Case 3: Singly even (n = 4k + 2)vector<vector<int>>fillSinglyEvenMagicSquare(intn){vector<vector<int>>mat(n,vector<int>(n));vector<vector<int>>half=fillOddMagicSquare(n/2);intadd=(n*n)/4;intk=(n-2)/4;// A (top-left)for(inti=0;i<n/2;i++)for(intj=0;j<n/2;j++)mat[i][j]=half[i][j];// C (top-right)for(inti=0;i<n/2;i++)for(intj=n/2;j<n;j++)mat[i][j]=half[i][j-n/2]+2*add;// D (bottom-left)for(inti=n/2;i<n;i++)for(intj=0;j<n/2;j++)mat[i][j]=half[i-n/2][j]+3*add;// B (bottom-right)for(inti=n/2;i<n;i++)for(intj=n/2;j<n;j++)mat[i][j]=half[i-n/2][j-n/2]+add;returnmat;}voidfillMagicSquare(intn,vector<vector<int>>&mat){if(n%2==1)mat=fillOddMagicSquare(n);elseif(n%4==0)mat=fillDoublyEvenMagicSquare(n);elsemat=fillSinglyEvenMagicSquare(n);}intmain(){intn=3;vector<vector<int>>mat;fillMagicSquare(n,mat);for(auto&row:mat){for(autox:row)cout<<x<<" ";cout<<endl;}}
Java
importjava.util.*;classGFG{// Case 1: Odd order magic square// Using Siamese methodstaticint[][]fillOddMagicSquare(intn){// initialize matrix with 0int[][]mat=newint[n][n];// Start position (middle row, last column)inti=n/2;intj=n-1;// Fill numbers from 1 to n*nfor(intnum=1;num<=n*n;){// If we go out of both bounds (special wrap case)if(i==-1&&j==n){i=0;j=n-2;}else{// Wrap columnif(j==n)j=0;// Wrap rowif(i==-1)i=n-1;}// If cell already filled ? move down-leftif(mat[i][j]!=0){i++;j-=2;continue;}// Place current numbermat[i][j]=num++;// Move diagonally up-righti--;j++;}returnmat;}// Case 2: Doubly even magic square (n % 4 == 0)staticint[][]fillDoublyEvenMagicSquare(intn){int[][]mat=newint[n][n];// Step 1: Fill matrix normally from 1 to n^2for(inti=0;i<n;i++)for(intj=0;j<n;j++)mat[i][j]=i*n+j+1;// Step 2: Replace selected cells with complement valuefor(inti=0;i<n;i++){for(intj=0;j<n;j++){// Pattern-based replacementif(((i%4==0||i%4==3)&&(j%4==1||j%4==2))||((i%4==1||i%4==2)&&(j%4==0||j%4==3))){// Replace with (n*n + 1 - current value)mat[i][j]=n*n+1-mat[i][j];}}}returnmat;}// Case 3: Singly even magic square (n = 4k + 2)staticint[][]fillSinglyEvenMagicSquare(intn){// used for swapping columnsintk=(n-2)/4;int[][]mat=newint[n][n];// Step 1: create smaller odd-order magic squareint[][]half=fillOddMagicSquare(n/2);// offset value for quadrantsintadd=(n*n)/4;// Divide matrix into 4 parts:// A | C// -----// D | B// A (top-left)for(inti=0;i<n/2;i++)for(intj=0;j<n/2;j++)mat[i][j]=half[i][j];// B (bottom-right)for(inti=n/2;i<n;i++)for(intj=n/2;j<n;j++)mat[i][j]=half[i-n/2][j-n/2]+add;// C (top-right)for(inti=0;i<n/2;i++)for(intj=n/2;j<n;j++)mat[i][j]=half[i][j-n/2]+2*add;// D (bottom-left)for(inti=n/2;i<n;i++)for(intj=0;j<n/2;j++)mat[i][j]=half[i-n/2][j]+3*add;// Swap left k columns between A and Dfor(inti=0;i<n/2;i++){for(intj=0;j<k;j++){inttemp=mat[i][j];mat[i][j]=mat[i+n/2][j];mat[i+n/2][j]=temp;}}// Swap right (k-1) columns between C and Bfor(inti=0;i<n/2;i++){for(intj=n-1;j>n-k;j--){inttemp=mat[i][j];mat[i][j]=mat[i+n/2][j];mat[i+n/2][j]=temp;}}// Final adjustment swapsinttemp=mat[n/4][0];mat[n/4][0]=mat[n-1-n/4][0];mat[n-1-n/4][0]=temp;temp=mat[n/4][n/4];mat[n/4][n/4]=mat[n-1-n/4][n/4];mat[n-1-n/4][n/4]=temp;returnmat;}publicstaticvoidfillMagicSquare(intn,int[][]mat){// Special case: n = 2 (not possible)if(n==2){for(inti=0;i<n;i++)Arrays.fill(mat[i],-1);return;}int[][]res;// Choose method based on nif(n%2==1)res=fillOddMagicSquare(n);elseif(n%4==0)res=fillDoublyEvenMagicSquare(n);elseres=fillSinglyEvenMagicSquare(n);// Copy result into original matrixfor(inti=0;i<n;i++)for(intj=0;j<n;j++)mat[i][j]=res[i][j];}// PRINT FUNCTIONvoidprint(int[][]mat,intn){}publicstaticvoidmain(String[]args){intn=3;int[][]mat=newint[n][n];fillMagicSquare(n,mat);for(inti=0;i<n;i++){for(intj=0;j<n;j++)System.out.print(mat[i][j]+" ");System.out.println();}}}
Python
# Case 1: Odd order magic square# Using Siamese methoddeffillOddMagicSquare(n):# initialize matrix with 0mat=[[0for_inrange(n)]for_inrange(n)]# Start position (middle row, last column)i=n//2j=n-1# Fill numbers from 1 to n*nnum=1whilenum<=n*n:# If we go out of both bounds (special wrap case)ifi==-1andj==n:i=0j=n-2else:# Wrap columnifj==n:j=0# Wrap rowifi==-1:i=n-1# If cell already filled ? move down-leftifmat[i][j]!=0:i+=1j-=2continue# Place current numbermat[i][j]=num# Move diagonally up-righti-=1j+=1num+=1returnmat# Case 2: Doubly even magic square (n % 4 == 0)deffillDoublyEvenMagicSquare(n):mat=[[0for_inrange(n)]for_inrange(n)]# Step 1: Fill matrix normally from 1 to n^2foriinrange(n):forjinrange(n):mat[i][j]=i*n+j+1# Step 2: Replace selected cells with complement valueforiinrange(n):forjinrange(n):# Pattern-based replacementif(((i%4==0ori%4==3)and(j%4==1orj%4==2))or((i%4==1ori%4==2)and(j%4==0orj%4==3))):# Replace with (n*n + 1 - current value)mat[i][j]=n*n+1-mat[i][j]returnmat# Case 3: Singly even magic square (n = 4k + 2)deffillSinglyEvenMagicSquare(n):# used for swapping columnsk=(n-2)//4mat=[[0for_inrange(n)]for_inrange(n)]# Step 1: create smaller odd-order magic squarehalf=fillOddMagicSquare(n//2)# offset value for quadrantsadd=(n*n)//4# Divide matrix into 4 parts:# A | C# -----# D | B# A (top-left)foriinrange(n//2):forjinrange(n//2):mat[i][j]=half[i][j]# C (top-right)foriinrange(n//2):forjinrange(n//2,n):mat[i][j]=half[i][j-n//2]+2*add# D (bottom-left)foriinrange(n//2,n):forjinrange(n//2):mat[i][j]=half[i-n//2][j]+3*add# B (bottom-right)foriinrange(n//2,n):forjinrange(n//2,n):mat[i][j]=half[i-n//2][j-n//2]+addreturnmatdeffillMagicSquare(n,mat):# Special case: n = 2 (not possible)ifn==2:foriinrange(n):forjinrange(n):mat[i][j]=-1return# Choose method based on nifn%2==1:res=fillOddMagicSquare(n)elifn%4==0:res=fillDoublyEvenMagicSquare(n)else:res=fillSinglyEvenMagicSquare(n)# Copy result into original matrixforiinrange(n):forjinrange(n):mat[i][j]=res[i][j]if__name__=="__main__":n=3mat=[[0for_inrange(n)]for_inrange(n)]fillMagicSquare(n,mat)# print matrixforrowinmat:print(*row)
C#
usingSystem;classGFG{// Case 1: Odd order magic square (Siamese method)staticint[,]fillOddMagicSquare(intn){int[,]mat=newint[n,n];inti=n/2;intj=n-1;for(intnum=1;num<=n*n;){if(i==-1&&j==n){i=0;j=n-2;}else{if(j==n)j=0;if(i==-1)i=n-1;}if(mat[i,j]!=0){i++;j-=2;continue;}mat[i,j]=num++;i--;j++;}returnmat;}// Case 2: Doubly even (n % 4 == 0)staticint[,]fillDoublyEvenMagicSquare(intn){int[,]mat=newint[n,n];for(inti=0;i<n;i++)for(intj=0;j<n;j++)mat[i,j]=i*n+j+1;for(inti=0;i<n;i++)for(intj=0;j<n;j++)if(((i%4==0||i%4==3)&&(j%4==1||j%4==2))||((i%4==1||i%4==2)&&(j%4==0||j%4==3)))mat[i,j]=n*n+1-mat[i,j];returnmat;}// Case 3: Singly even (n = 4k + 2)staticint[,]fillSinglyEvenMagicSquare(intn){int[,]mat=newint[n,n];int[,]half=fillOddMagicSquare(n/2);intadd=(n*n)/4;intk=(n-2)/4;for(inti=0;i<n/2;i++)for(intj=0;j<n/2;j++)mat[i,j]=half[i,j];for(inti=0;i<n/2;i++)for(intj=n/2;j<n;j++)mat[i,j]=half[i,j-n/2]+2*add;for(inti=n/2;i<n;i++)for(intj=0;j<n/2;j++)mat[i,j]=half[i-n/2,j]+3*add;for(inti=n/2;i<n;i++)for(intj=n/2;j<n;j++)mat[i,j]=half[i-n/2,j-n/2]+add;returnmat;}// FINAL FUNCTION (required signature)staticvoidfillMagicSquare(intn,int[,]mat){int[,]result;if(n%2==1)result=fillOddMagicSquare(n);elseif(n%4==0)result=fillDoublyEvenMagicSquare(n);elseresult=fillSinglyEvenMagicSquare(n);for(inti=0;i<n;i++)for(intj=0;j<n;j++)mat[i,j]=result[i,j];}staticvoidMain(){intn=3;int[,]mat=newint[n,n];fillMagicSquare(n,mat);for(inti=0;i<n;i++){for(intj=0;j<n;j++)Console.Write(mat[i,j]+" ");Console.WriteLine();}}}
JavaScript
// Case 1: Odd order magic square// Using Siamese methodfunctionfillOddMagicSquare(n){// initialize matrix with 0letmat=Array.from({length:n},()=>Array(n).fill(0));// Start position (middle row, last column)leti=Math.floor(n/2);letj=n-1;// Fill numbers from 1 to n*nfor(letnum=1;num<=n*n;){// If we go out of both bounds (special wrap case)if(i==-1&&j==n){i=0;j=n-2;}else{// Wrap columnif(j==n)j=0;// Wrap rowif(i==-1)i=n-1;}// If cell already filled ? move down-leftif(mat[i][j]!=0){i++;j-=2;continue;}// Place current numbermat[i][j]=num++;// Move diagonally up-righti--;j++;}returnmat;}// Case 2: Doubly even magic square (n % 4 == 0)functionfillDoublyEvenMagicSquare(n){letmat=Array.from({length:n},()=>Array(n).fill(0));// Step 1: Fill matrix normally from 1 to n^2for(leti=0;i<n;i++){for(letj=0;j<n;j++){mat[i][j]=i*n+j+1;}}// Step 2: Replace selected cells with complement valuefor(leti=0;i<n;i++){for(letj=0;j<n;j++){// Pattern-based replacementif(((i%4==0||i%4==3)&&(j%4==1||j%4==2))||((i%4==1||i%4==2)&&(j%4==0||j%4==3))){// Replace with (n*n + 1 - current value)mat[i][j]=n*n+1-mat[i][j];}}}returnmat;}// Case 3: Singly even magic square (n = 4k + 2)functionfillSinglyEvenMagicSquare(n){// used for swapping columnsletk=(n-2)/4;letmat=Array.from({length:n},()=>Array(n).fill(0));// Step 1: create smaller odd-order magic squarelethalf=fillOddMagicSquare(Math.floor(n/2));// offset value for quadrantsletadd=(n*n)/4;// Divide matrix into 4 parts:// A | C// -----// D | B// A (top-left)for(leti=0;i<n/2;i++)for(letj=0;j<n/2;j++)mat[i][j]=half[i][j];// C (top-right)for(leti=0;i<n/2;i++)for(letj=n/2;j<n;j++)mat[i][j]=half[i][j-n/2]+2*add;// D (bottom-left)for(leti=n/2;i<n;i++)for(letj=0;j<n/2;j++)mat[i][j]=half[i-n/2][j]+3*add;// B (bottom-right)for(leti=n/2;i<n;i++)for(letj=n/2;j<n;j++)mat[i][j]=half[i-n/2][j-n/2]+add;returnmat;}// MAIN FUNCTIONfunctionfillMagicSquare(n,mat){// Special case: n = 2 (not possible)if(n==2){for(leti=0;i<n;i++)for(letj=0;j<n;j++)mat[i][j]=-1;return;}letres;// Choose method based on nif(n%2==1)res=fillOddMagicSquare(n);elseif(n%4==0)res=fillDoublyEvenMagicSquare(n);elseres=fillSinglyEvenMagicSquare(n);// Copy result into original matrixfor(leti=0;i<n;i++)for(letj=0;j<n;j++)mat[i][j]=res[i][j];}// DRIVER CODE letn=3;letmat=Array.from({length:n},()=>Array(n).fill(0));fillMagicSquare(n,mat);// print matrixfor(leti=0;i<n;i++){console.log(mat[i].join(" "));}