看完最强大脑,有一期是说N阶幻立方的,作为一个程序员,我的第一反应时我可以用程序实现,在此公布N(奇数)阶幻方的java实现代码:
package com.lzugis.test; public class Practice { public static int[][] magicOdd(int n) { int[][] square = new int[n + 1][n + 1]; int i = 0; int j = (n + 1) / 2; for (int key = 1; key <= n * n; key++) { if ((key % n) == 1) i++; else { i--; j++; } if (i == 0) i = n; if (j > n) j = 1; square[i][j] = key; } int[][] matrix = new int[n][n]; for (int k = 0; k < matrix.length; k++) { for (int l = 0; l < matrix[0].length; l++) { matrix[k][l] = square[k + 1][l + 1]; } } return matrix; } public static void main(String[] args) { int[][] magic = Practice.magicOdd(3); for (int k = 0; k < magic.length; k++) { for (int l = 0; l < magic[0].length; l++) { System.out.print(magic[k][l] + " "); } System.out.println(); } } }效果如下:
3阶幻方
5阶幻方
备注:
幻方(Magic Square)是一种将数字安排在正方形格子中,使每行、列和对角线上的数字和都相等的方法。幻方中间格的值为(N*N+1)/2,即3阶幻方中间为(3*3+1)/2=5,3阶幻方中间为(5*5+1)/2=13,……
如有疑问请联系:
QQ:1004740957
Email:niujp08@qq.com
原文地址:http://blog.csdn.net/gisshixisheng/article/details/43303049