Number spiral diagonals
Problem 28
Starting with the number 1 and moving to the right in a clockwisedirection 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 13
It 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 spiralformed 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的螺旋中对角线上数字之和是多少?
首先刚拿到这道题的时候我觉的自己应该是搞不定的,因为欧拉计划大多都是数学问题我觉得我的线性代数还没有那么优秀,最起码不是特别熟的那种,更何况线代是上学期的课程感觉忘得已经差不多了。
然后我又想起来欧拉计划的前几题是可以通过暴力枚举来搞定的,然后我就先生成一个1001×1001的行列式再两重循环求主对角线和副对角线之和可是不知道为什么程序就是执行不出来
备注:后来在一本算法书上看到把过大的数组放到main函数外面才可以运行
这套操作不能奏效那就换一种方法呗:
然后这道题就变成了一道找规律的题
这是一个n×n矩阵
当n=1时,右上角的元素为1(只有一个元素1所以右上角的元素为1)
当n=2,时右上角元素为9,左上角元素为7,左下角元素为5,右下角元素为3
当n=5时,右上角元素为25,左上角元素为21,左下角元素为17,右下角元素为13
我们现在就可以得出结论:左上角比右上角元素少n-1,左下角比左上角少n-1,右下角比左下角少n-1
所以我们可以得到右上角的元素为n×n,左上角的元素为n×n-n+1,左下角的元素为n×n-n+1-n+1,右下角的元素为n×n-n+1-n+1-n+1
我在寒假时看一些算法的东西然后那上面有一种很重要的算法思想就是:分治思想
我个人认为分治思想就是把问题自顶向下层层细化,当问题细化到可以解决的时候再自底向下层层解决,我觉得这个东西说白了就是递归吧。
当求(n)×(n)矩阵的对角线之和时就是四个角的值再加上(n-2)×(n-2)的对角线之和的值,求(n-2)×(n-2)的对角线之和的值就是四个角的值再加上(n-4)×(n-4)对角线的值,以此类推一直到n=1,时就自底向上层层解决
所以可得代码:
#include<stdio.h>
long long sumOfDiagonal(int n)
{
if(n == 1) return 1;
else return 4 * n * n - 6 * n + 6 + sumOfDiagonal(n - 2);
}
int main()
{
long long t = sumOfDiagonal(1001);
printf("%lld",t);
}
然后这是大佬的代码:
#include <iostream>
#include <cinttypes>
using std::cin;
using std::cout;
using std::endl;
int main() {
int64_t sum = 1;
for (int64_t i = 3; i <= 1001; i += 2) {
sum += 4 * i * i - 6 * i + 6;
}
printf("%" PRId64 "\n", sum);
return 0;
}
竟然和我的一毛一样不过我用的是递归他用的是循环
![大笑](https://static-blog.csdn.net/xheditor/xheditor_emot/default/laugh.gif)