Number spiral diagonals


Fork me on GitHub
2014-09-18

Problem 028: Number spiral diagonals

Description:

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?


Solution:
0"d"55+*1+::1-01p*>:01g-:01g-:01g-:01g-:1-#v_>\# :#+_+.@
X                 ^p10-2g10                <
Start
??
Pause
Reset
Output:
Stack:   (0)

Explanation:

Let's look ate the diagonal numbers of our 5x5 grid:

n info
25 starting number
21 = 25 - 4
17 = 21 - 4
13 = 17 - 4
9 = 13 - 4
7 = 9 - 2
5 = 7 - 2
3 = 5 - 2
1 = 3 - 2

You can probably see the pattern here. The rest of the algorithm is simply loop from 1001^2 to 1, subtracting the right amount each round and in the end summing up all numbers.

I have this little code to calculate the sum of stack values until a zero is encountered:

>\# :#+_+

Perhaps it's useful for someone else.


Interpreter steps: 28 514
Execution time (BefunExec): 15ms (1.90 MHz)
Program size: 54 x 2 (fully conform befunge-93)
Solution: 669171001
Solved at: 2014-09-18



made with vanilla PHP and MySQL, no frameworks, no bootstrap, no unnecessary* javascript