Level n odd magic square
/* Level 3 matrix
3*3 matrix, with a constant value (15)
Analysis:
Create a 3*3 two-dimensional array a [3] [3], assign num = 1 to a [0] [1], and save its subscript, the value in the upper-right corner of a [0] [1] is equal to num ++, which loops in sequence,
The subscript will definitely be out of the range.
Int ki = (I-1 + 3) % 3;
Int kJ = (J + 1) % 3;
It can be solved
If an element exists in the upper-right corner, the num ++ value is assigned to the position at the bottom of the element.
*/
# Include <iostream>
Using namespace STD;
Int main ()
{
Int I, J;
Int kN;
While (1)
{
Cout <"input odd magic level :";
Cin> kN;
While (1) // judge whether the input is odd
{
If (kN % 2 = 0 | kN <2)
{
Cout <"input data error! Enter the odd number again :";
Cin> kN;
}
Else
{
Break;
}
}
Int ** A = new int * [kN]; // dynamically allocates two-dimensional arrays.
For (I = 0; I <kN; I ++)
{
A [I] = new int [kN];
For (j = 0; j <kN; j ++)
{
A [I] [J] = 0; // array Initialization is 0
}
}
// Fixed the position of the middle column of the first row as 1
Int num = 1;
I = 0;
J = KN/2;
A [0] [J] = num;
While (Num <kN * kN)
{
Num ++;
Int ki = (I-1 + kN) % kN; // Save the X, Y coordinates in the upper right corner
Int kJ = (J + 1) % kN;
If (A [Ki] [kJ] = 0) // If the element in the upper right corner is empty (no data is filled yet)
{
A [Ki] [kJ] = num;
I = Ki;
J = kJ;
}
Else // If an element exists in the upper-right corner, it is placed at the bottom of it.
{
I = (KI + 2) % kN;
J = (KJ-1 + kN) % kN; // The addition of Kn cycles is required for subtraction.
A [I] [J] = num;
}
}
// Output array elements
For (INT m = 0; m <kN; m ++)
{
For (INT n = 0; n <kN; n ++)
{
Cout <
[N] <"";
}
Cout <Endl;
}
// Output results with no columns in each row
Int sum = 0;
For (int g = 0; G <kN; G ++)
{
Sum = sum + A [0] [g];
}
Cout <"the sum of each column in each row and its diagonal line:" <sum <Endl;
}
System ("pause ");
Return 0;
}