Magic Square
Algorithm
odd_num(n)//creates magic square for odd number n 1. [initialize segment variables] num=1 and nn=n*3/2; 2. Repeat for i=0 to n a. Repeat for j=0 to n i. Set m[(j-i+nn)%n][(i*2-j+n)%n]=num++; 3. [End] even_num( n)//creates magic square for even number n 1. [initialize segment variables] num:=1, nminus:=n-1,nmiddle:=n/2,nn=n*n+1 and osl:=0. 2. Set first_block:=(n-2)/4, second_block=nminus-first_block. 3. Set first_inside=n/4, second_inside=nminus-first_inside. 4. Repeat for j=0 to n a. Repeat for i=0 to n i. If(i >= first_inside && i <= second_inside && j >= first_inside && j <= second_inside) then Set m[i][j]:=num. ii. else if((i > first_block && i < second_block) || (j > first_block && j < second_block)) then Set m[i][j]:= nn-num. iii. else Set m[i][j]=num; iv. [Increase num]. 5. If(!(n%4)) then return; 6. Set switch_row[0]=random(nmiddle-1)+first_block+1; 7. Set switch_row[1]=random(nmiddle-1); 8. If(switch_row[1] >= first_block) then Set switch_row[1]+=(nmiddle+1); 9. Set last_switch_column=random(nmiddle-1); 10. If(last_switch_column >= first_block) then Set last_switch_column+=(nmiddle+1); 11. Repeat for i=0 to nmiddle a. If(i==first_block || i==second_block) then: i. Set osl=1-osl and continue. b. CALL swap(second_block, i, second_block, nminus-i); c. CALL swap(i, first_block, nminus-i, first_block); d. CALL swap(i, second_block, nminus-i, second_block); e. CALL swap(i, switch_row[osl], nminus-i, switch_row[osl]); 12. Repeat for i=first_block+1 to i < second_block a. CALL swap(first_block, i, second_block, i); b. CALL swap(i, first_block, i, second_block); 13. CALL swap(first_block, nmiddle, second_block, nmiddle); 14. CALL swap(last_switch_column, first_block, last_switch_column, second_block); 15. [end] swap( i1, j1,i2, j2)//swaps values at mi1j1 with value at mi2j2 1. [interchange m[i1][j1] with m[i2][j2] a. Set k := m[i1][j1]; b. Set m[i1][j1]=m[i2][j2]; c. Set m[i2][j2]=k; 2. [end]
Algorithm Description
JAVA Code
/*Magic Box Problem*/
import java.io.*;
class magic
{
public static void main(String args[])throws IOException
{
int n,i,j,k,nsqr;
System.out.println("Enter the order of matrix");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
n=Integer.parseInt(br.readLine());
nsqr=n*n;
int a[][]=new int[n][n];
i=0;
j=n/2;
for(k=1;k<=nsqr;k++)
{
a[i][j]=k;
i--;
j++;
if(k%n==0)
{
i+=2;
j--;
}
else if(j==n)
j-=n;
else if(i<0)
i+=n;
}
System.out.println("The resultant magic box is:");
for(i=0;i<n;i++)
{
System.out.print("\n");
for(j=0;j<n;j++)
System.out.print(" "+ a[i][j]);
}
}
}