Number spiral diagonals
Problem 28
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 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 spiral formed in the same way?
刚开始读题的时候还觉得有点麻烦呢,后面发现规律以后觉得就一水题了……从内环1,3,5,7,9每个数加b=2就得下一个数,到第二环的时候13,17,21,25,也就是第一环最大的数是9,从内环出来又加b+=2就是4,9+4=13,而13正好是第二环的第一个数,第三环就是第二环最大的数25+=(b+=2)就等于31,此时b=6……同理就可得到下面所有的数了,执行上下各500行就得结果……如下代码:
#include <iostream>
#include <cmath>
#include<algorithm>
using namespace std;
int main()
{
int k=1,j=0,a=1,b=2,sum=1;//k初始化为第一环,刚开始a等于最里面那个数就是1,b为第个环间的差值,sum等于最里面的那个数就是1,因为等下开始a就变了,故……
while(k++<=2000) //每环有4个数,而要执行500行,因为第一行是1就一个数,本来是501行,但是里面那行已经处理,故执行500就得了,有:4*500=2000
{
j++;
a+=b;
sum+=a;
if(j%4==0) b+=2; //因为每一环有四个数,所以当正好四个数完的时候b就增2到下一环
//cout<<sum<<endl;
}
cout<<sum<<endl;
return 0;
}