Question
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?
Haskell
main :: IO ()
= print $ foldr (+) 1 [4*n^2 - 6*n + 6 | n <- [3,5..1001]] main
$ ghc -O2 -o spiral spiral.hs
$ time ./spiral
real 0m0.002s
user 0m0.002s
sys 0m0.000s
Python
#!/usr/bin/env python
def sum_diagonals_of_spiral(size):
= 1
n = 2
step = 0
total = 0
since_last while n <= size**2:
+= n
total += step
n += 1
since_last if since_last == 4:
+= 2
step = 0
since_last return total
print(sum_diagonals_of_spiral(1001))
$ time python3 spiral.py
real 0m0.017s
user 0m0.017s
sys 0m0.000s
Ruby
#!/usr/bin/env ruby
= 1
i = i
sum = 2
step until i >= 1001**2
4.times { sum += i += step }
+= 2
step end
puts sum
$ time ruby spiral.rb
real 0m0.039s
user 0m0.023s
sys 0m0.016s
Rust
fn main() {
let sum = (1..501)
.map(|i| {
let n = 2 * i + 1;
4 * n * n - 6 * n + 6
})
.sum::<u64>() + 1;
println!("{}", sum);
}
$ rustc -C target-cpu=native -C opt-level=3 -o spiral spiral.rs
$ time ./spiral
real 0m0.001s
user 0m0.000s
sys 0m0.001s