Number spiral diagonals
Starting with the number 1 and moving to the right in a clockwise direction, a 5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13It can be verified that the sum of the numbers on the diagonals is 101.
What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?
螺旋数阵对角线
从1开始,按顺时针顺序铺开的5×5螺旋数阵如下所示:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13可以看出,该数阵对角线上的数之和是101。
考虑以同样方式构成的1001×1001螺旋数阵,其对角线上的数之和是多少?
这个题的解题思路非常简单,可以从这个矩阵的圈来入手:
每圈的边长等于
m是边长,n是第几圈;
每圈右上角的数等于边长的平方,那么就可以推断出这一圈4个角的数,分别为:
这一圈的4个角之和为:
,但是第一圈不适用于这个代码,因为只有1;好的这下写代码就变得非常的简单了,下面是代码实现:
#include <stdio.h> #define MAX_N 1001 int main() { int n = MAX_N / 2 + 1;//求得有多少圈 int ans = 1;//直接最中间的一圈赋给答案,从第二圈开始计算 for (int i = 2; i <= n; i++) { int m = 2 * i - 1; ans += 4 * m * m - 6 * m + 6; } printf("%d\n", ans); return 0; }
最终答案:669171001