[Project Euler] 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?

好吧,这道题我真不知道该怎样用C++编写

就说说计算思路吧

5X5的方阵计算如下:

1+(6+19)× 4   = (1+6+19)× 4 -3

        = ((2*0)^2 +1 +(2*1)^2+2 +(2*2)^2 +3) *4 -3

        =16*(0^2+1^2+2^2) + 4*(1+2+3) -3

好啦,平方和公式大家都知道吧 n*(n+1)*(2*n+1)/6

那1001×1001的方阵的对角和:

16*(500*501*1001)/6 + 4*(501*502)/2 -3

在python上简单的计算得到最后结果:

      669171001

整个过程不超过1分钟。写这篇文章就花了3分钟

原文链接: https://www.cnblogs.com/xianglan/archive/2011/03/27/1997056.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    [Project Euler] Problem 28

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/22924

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 上午12:54
下一篇 2023年2月8日 上午12:55

相关推荐