Problem 28

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:

[color=red]21[/color] 22 23 24 [color=red]25[/color]
20 [color=red]7[/color] 8 [color=red]9[/color] 10
19 6 [color=red]1[/color] 2 11
18 [color=red]5[/color] 4 [color=red]3[/color] 12
[color=red]17[/color] 16 15 14 [color=red]13[/color]

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?

[code=ruby]h,v = 1,0
a,b = 1,1
side = 1001
$tab = Array.new(side+2)
(0…(side+1)).each do |e|
$tab[e] = Array.new(side+2, nil)
$tab[e][0], $tab[e][side+1] = 0,0
end
$tab[0], $tab[side+1] = Array.new(side+2, 0), Array.new(side+2, 0)

((side**2).downto(1)).each do |n|
$tab[a][b] = n
if $tab[a+v][b+h] != nil
if h==0
if v==1
h,v = -1,0
else
h,v = 1,0
end
elsif v==0
if h==1
h,v = 0,1
else
h,v = 0,-1
end
end
end
a,b = a+v, b+h
break if $tab[a][b] != nil
end
sum = 0
1.upto(side) do |a|
sum += $tab[a][a]
sum += $tab[a][side+1-a]
end
sum -= $tab[(side+1)/2][(side+1)/2]

puts “suma: #{sum}”[/code]

[code=ruby]num = 1001**2
sum = 0
n = 1000
$tmp = num
while n >= 2
4.times do
sum += $tmp-n
$tmp -= n
end
n -= 2
end

puts sum += num[/code]

Wersja dla 1.8.7/1.9

[code=ruby]def diagonals
a, b = 1, 0
(1…4).cycle do |c|
b +=2 if c == 1
yield a
a += b
end
end

puts enum_for(:diagonals).take(2001).inject(:+)[/code]

[code=ruby]def ring(n)
n2 + (n2 - (n-1)) + (n2 - 2*(n-1)) + (n2 - 3*(n-1))
end

sum = 1
x = 1001
while x > 1
sum += ring(x)
x -= 2
end

p sum[/code]