project euler problem 28

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?


Answer:
669171001
Completed on Fri, 11 Oct 2013, 05:53

刚开始读题的时候还觉得有点麻烦呢,后面发现规律以后觉得就一水题了……从内环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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值