I want to write a program to work out how many semi-magic squares there are.
Here is the definition of semi-magic squares
If we define \$H_n(t)\$ is the number of semi magic squares which satisfy:
- The square is \$n*n\$ dimension
- The sum of each row elements and sum of each column elements equal to \$t\$
The first idea came to me is brute force searching. I know backtracing may be better, but I don't know how to write the program.
For example, when \$n = 3\$, \$t = 1\$.
The third constraint:
I need to clearly point out that all the matrix elements are non-negative integers. Apparently, we can get that elements \$\in[0,t]\$
According to this, we can get this table:
n\t | 1|2|3|4|5|6|7|8 ---------| ----- 1 | 1|1|1|1|1|1|1|1 2 | 2|3|4|5|6|7|8|9 3 | 6|21|55|120|231|406|666|1035 4 | 24|282|2008|10147|40176|132724|381424|981541
When \$n = 3\$, it's something like this sequence.
#include<iostream>
using namespace std;
int square[3][3];
//check whether it is a semi-square
bool final_check(int n,int t)
{
for(int i=0;i<n;i++)
{
int sum_col=0;
int sum_row=0;
for(int j=0;j<n;j++)
{
sum_row+=square[i][j];
sum_col+=square[j][i];
}
if(sum_col!=t||sum_row!=t)
return false;
}
return true;
}
void display(int n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
cout<<square[i][j]<<"\t";
cout<<endl;
}
cout<<"************"<<endl;
}
//count \$H_3(1)\$
int main()
{
int n=3,t=5;
int total_num=0;
for(int a=0;a<=t;a++)
{
square[0][0]=a;
for(int b=0;b<=t;b++)
{
square[0][1]=b;
for(int c=0;c<=t;c++)
{
square[0][2]=c;
for(int d=0;d<=t;d++)
{
square[1][0]=d;
for(int e=0;e<=t;e++)
{
square[1][1]=e;
for(int f=0;f<=t;f++)
{
square[1][2]=f;
for(int g=0;g<=t;g++)
{
square[2][0]=g;
for(int h=0;h<=t;h++)
{
square[2][1]=h;
for(int i=0;i<=t;i++)
{
square[2][2]=i;
if(final_check(n,t)) //check
{
display(n);
total_num++;
}
}
}
}
}
}
}
}
}
}
cout<<"total number of semi magic square: "<<total_num<<endl;
getchar();
return 0;
}
I know that my code is very bad. Could anyone help me improve the code? There are so many for
loops. If \$n = 5\$, I would have to write 25 for
loops.
Does anyone have a better solution?