### Project Euler - Problem 28

**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**

//calculates the sum for the level of the square

//each increase in level only requires calculating 4 new values, the corners

let levelValue (start:int) (side:int) =

let diffAtLevel = side - 1

let sum = (start + diffAtLevel) + (start + (diffAtLevel * 2)) + (start + (diffAtLevel * 3)) + (start + (diffAtLevel * 4))

sum

//recursively iterates from level 0, which is the center

//to the outer part of the array

//and for each level calculates the additional sum and sums that to running sum

let rec sumByPowers start priorLevelSquared level endSide sum =

if level > endSide then

sum

else

let newSum = sum + levelValue priorLevelSquared level

sumByPowers start (level * level) (level + 2) endSide newSum

let resultTest = sumByPowers 0 0 1 1001 1

## Comments

## Post a Comment