TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
输出魔幻正方形(直向、纵向、斜向数自相加均相等)。
一、奇数行的魔幻正方形
第1个数放在第1行第1列的中间,然后向右上填,如果右上已有数字,则向下填,为了计算方便,我
们利用索引1至N,而不是0至N-1,而在计算是向右上或向下时,可以将索引值除以N值,如果得到余
数为1就向下,否则就往右上。
- public class MagicSquare{
- public static void main(String args[]){
- int N = 5;
- int i, j, key;
- int square[][] = new int[N+1][N+1];
- i = 0;
- j = (N+1) / 2;
- for(key = 1; key <= N*N; key++) {
- if((key % N) == 1){
- i++;
- } else {
- i--;
- j++;
- }
- if(i == 0) // 到了最顶,将i变成最尾行
- i = N;
- if(j > N) // 到了最右,�j变成最左行
- j = 1;
- square[i][j] = key;
- }
- for(i = 1; i <= N; i++) {
- for(j = 1; j <= N; j++){
- System.out.print(square[i][j] + " ");
- // jdk1.5有提供System.out.printf的功能,不错哦.以后排版就好看多了.
- // System.out.printf("%2d ",square[i][j]);
- }
- System.out.println();
- }
- }
- }
复制代码 运行结果:
D:java>java MagicSquare
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 D:java> D:java> 二、行数为4N的魔幻正方形- 刚刚说了单数魔幻正方形的方法.
- 现在说说4N的方法.
- 一个从左上由1依序开始填,以上至下,左至右,但遇对角线不填。
- ? 2 3 ?
- 5 ? ? 8
- 9 ? ? 12
- ? 14 15 ?
- 另一个由左上由16依减速序开始填,上至下,左至右,但只填在对角线。
- 16 ? ? 13
- ? 11 10 ?
- ? 7 6 ?
- 4 ? ? 1
- 再将两个合起来就是答案。
- 16 2 3 13
- 5 11 10 8
- 9 7 6 12
- 4 14 15 1
- 左上至右下:j % 4 == i % 4
- 右上至左下:(j % 4 + i % 4) == 1
- 代�:
- public class MagicSquare{
- public static void main(String args[]){
- int N=4;
- int i, j;
- int square[][] = new int[N+1][N+1];
- for(j = 1; j <= N; j++) {
- for(i = 1; i <= N; i++){
- if(j % 4 == i % 4 || (j % 4 + i % 4) == 1)
- square[i][j] = (N+1-i) * N -j + 1;
- else
- square[i][j] = (i - 1) * N + j;
- }
- }
- for(i = 1; i <= N; i++) {
- for(j = 1; j <= N; j++)
- System.out.print(square[i][j] + " ");
- System.out.println();
- }
- }
- }
-
复制代码 三、 上面解了单数和4N魔幻正方形。
那只剩下2(2N+1)的未解.
有了这两个方法, 2(2N+1)你自己想想吧.
function TempSave(ElementID)
{
CommentsPersistDiv.setAttribute("CommentContent",document.getElementById(ElementID).value);
CommentsPersistDiv.save("CommentXMLStore");
}
function Restore(ElementID)
{
CommentsPersistDiv.load("CommentXMLStore");
document.getElementById(ElementID).value=CommentsPersistDiv.getAttribute("CommentContent");
} |
|