Solving algoritm spiral (in Python)

154 Views Asked by At

Good time a day.

Could you explain how to solve this task, which you can see by that link: https://www.codewars.com/kata/61559bc4ead5b1004f1aba83/train/python ?

I couldn`t solve it and unlock solution of case. The best practice was

def spiral_sum(size):
    return (size + 1) * (size + 1) // 2 - 1

I don`t understand the best solution.

Could you explain this formula? I know that is more mathematic then programming, but I don`t understand the idea of solution.

Thank you for help.

2

There are 2 best solutions below

0
On BEST ANSWER

I would solve it recursively.

For odd values, $f(n) = n^2 - f(n-2) - 1$

For even values, $f(n)=n^2 - f(n-2) - 2$

1
On

I just found a little about sequence in https://oeis.org/A047838.

Here is the description of the formula.

The main idea of kata is to create sequence from the length of spiral. For example m= [1, 3, 7, 11, 17 ...] is the length(n) of index (i (starts from 1) in list (m), which you can describe by using this formula: a(i) = floor(n^2/2)-1.

We have:

i = 5+1

And got result:

a(i) = floor(6^2/2)-1 = 17