#include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char *argv[]) { int i; int n = 0; int width; int row, col; int *array; char buf[64]; if (argc != 2) { printf("usage:\n"); printf("\t%s <an odd number>\n", argv[0]); return 1; } n = atoi(argv[1]); if ((n & 1) == 0) { printf("error: odd number expected\n"); return 1; } array = (int *)malloc(n * n * sizeof(int)); if (array == NULL) { perror("malloc()"); return 1; } for (i = 0; i < n * n; i++) { array[i] = 0; } for (i = 1, row = 0, col = n >> 1; i <= n * n; i++) { array[row * n + col] = i; if (array[(row + n - 1) % n * n + (col + 1) % n]) { row = (row + 1) % n; } else { row = (row + n - 1) % n; col = (col + 1) % n; } } sprintf(buf, "%d", n * n); width = 1 + strlen(buf); for (row = 0; row < n; row++) { for (col = 0; col < n; col++) { printf("%*d", width, array[row * n + col]); } printf("\n"); } return 0; } |
运行示例:
$ ./magic 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