Problem 28
11 October 2002
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 both diagonals is 101.
What is the sum of both diagonals in a 1001 by 1001 spiral formed in the same way?
def fun28():
#(ard, ald, alu, aru)分别代表右下、左下、左上、右上的数值
#都初始化为1
(ard, ald, alu, aru) = (1, 1, 1, 1)
#1001*1001的矩阵,共有层次500层(旋转500圈)
step = 0
result = 1
for i in range(500):
ard = ard + 3*step + (step+2)*1
ald = ald + 2*step + (step+2)*2
alu = alu + 1*step + (step+2)*3
aru = aru + 0*step + (step+2)*4
step += 2
result += ard+ald+alu+aru
return result
其实我们令右上角aru=
n2,则alu=
n2-n+1, ald=
n2-2n+2, ard=
n2-3n+3, n取3到1001, 步长为2
answer is 669171001
阅读(375) | 评论(0) | 转发(0) |