Solving magic problem
Magic is an ancient mathematical game. The magic of order n refers to the integer 1 ~ N2 is arranged into a matrix of n × N, so that the sum of each element in each row, the sum of each element in each column, and the elements on the two diagonal lines are the same number of S. S is the magic and. In medieval Europe, there was a mysterious idea of magic, and many people wore magic to avoid evil. The construction method of the odd level Magic Square is very simple. Let's look at a third level Magic Square first ,:
The positions of the numbers in the square matrix can be determined as follows:
First, place 1 in the square in the middle of the top row, and then place the next integer in the upper right corner. If the last row is reached, the next integer is placed in the last row, it is like it is on the top of the first line. If it reaches the rightmost end, the next integer is placed on the leftmost end, as if it is on the right of the rightmost column, when a number is entered in the square, the next integer is placed at the bottom of the square that is just filled with a number. Take a look at the third-level Magic Square from 1 to 9 to understand its construction method. below isProgram:
# Define Max 15
# Include < Stdio. h >
Void Main ( Void )
{
Int M, mm, I, J, K, Ni, NJ;
Int Magic [Max] [Max];
Printf ( " Enter the number you wanted \ n " );
Scanf ( " % D " , & M );
For (I = 0 ; I < M; I ++ ) // Initialization
For (J = 0 ; J < M; j ++ )
Magic [I] [J] = 0 ;
If (M > 0 ) && (M % 2 ! = 0 )) // Odd Order
{
Mm = M * M;
I = 0 ; // Position of the first value
J = M / 2 ;
For (K = 1 ; K <= Mm; k ++ )
{
Magic [I] [J] = K;
// Calculates the coordinates of the upper right square.
If (I = 0 ) // Top Line
Ni = M - 1 ; // The next position is in the bottom row
Else
Ni = I - 1 ;
If (J = M - 1 ) // Rightmost
NJ = 0 ; // The next position is at the leftmost end.
Else
NJ = J + 1 ;
// Check whether the number of squares exists in the upper right corner.
If (MAGIC [Ni] [NJ] = 0 ) // No value in the upper right corner
{
I = Ni;
J = NJ;
}
Else // Number of squares filled in the upper right corner
I ++ ;
}
For (I = 0 ; I < M; I ++ )
{
For (J = 0 ; J < M; j ++ )
Printf ( " % 4D " , Magic [I] [J]);
Printf ( " \ N " );
}
}
Else // M <= 0 or M _ is an even number
Printf ( " Error in input data. \ n " );
}
taking input value 5 as an example, the program runs as follows:
enter the number you wanted
5
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9