java实现三阶幻方,使其对角线,横,纵的和相等
时间: 2024-03-27 21:35:49 浏览: 19
好的,以下是 Java 实现三阶幻方的示例代码:
```java
public class MagicSquare {
private int[][] square;
private int n;
public MagicSquare(int n) {
this.n = n;
this.square = new int[n][n];
}
public void generate() {
int row = n - 1;
int col = n / 2;
for (int i = 1; i <= n * n; i++) {
square[row][col] = i;
int newRow = (row + 1) % n;
int newCol = (col + 1) % n;
if (square[newRow][newCol] == 0) {
row = newRow;
col = newCol;
} else {
row = (row - 1 + n) % n;
}
}
}
public void print() {
for (int row = 0; row < n; row++) {
for (int col = 0; col < n; col++) {
System.out.print(square[row][col] + "\t");
}
System.out.println();
}
}
public boolean check() {
int sum = n * (n * n + 1) / 2;
for (int i = 0; i < n; i++) {
int rowSum = 0;
int colSum = 0;
for (int j = 0; j < n; j++) {
rowSum += square[i][j];
colSum += square[j][i];
}
if (rowSum != sum || colSum != sum) {
return false;
}
}
int diagSum1 = 0;
int diagSum2 = 0;
for (int i = 0; i < n; i++) {
diagSum1 += square[i][i];
diagSum2 += square[n - 1 - i][i];
}
return diagSum1 == sum && diagSum2 == sum;
}
public static void main(String[] args) {
MagicSquare magicSquare = new MagicSquare(3);
magicSquare.generate();
magicSquare.print();
if (magicSquare.check()) {
System.out.println("This is a magic square!");
} else {
System.out.println("This is not a magic square.");
}
}
}
```
这个示例代码中,我们使用了一个叫做“魔方阵”的算法来生成三阶幻方。在 `generate` 方法中,我们从最后一行的中间位置开始,逐步填写数字,直到填满整个矩阵。我们使用了一个公式来计算下一个需要填写的位置,如果下一个位置已经被填写了数字,就将当前位置向上移动一行。
在 `print` 方法中,我们简单地打印出生成的幻方。
在 `check` 方法中,我们检查每行、每列和两个对角线的和是否都相等。如果相等,就说明这是一个幻方,返回 `true`。否则,返回 `false`。
在 `main` 方法中,我们创建了一个 `MagicSquare` 对象,使用 `generate` 方法生成幻方,并且使用 `print` 方法打印出来。最后,我们使用 `check` 方法检查这是否是一个幻方,打印出相应的信息。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)