Efficiency of Project Euler 28 - number spiral diagonals I have written a solution for 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:
  
  $$\begin{array}{rrrrr}
\color{red}{21} &amp;22 &amp;23 &amp;24 &amp;\color{red}{25}\\
20 &amp; \color{red}{7} &amp; 8 &amp; \color{red}{9} &amp;10\\
19 &amp; 6 &amp; \color{red}{1} &amp; 2 &amp;11\\
18 &amp; \color{red}{5} &amp; 4 &amp; \color{red}{3} &amp;12\\
\color{red}{17} &amp;16 &amp;15 &amp;14 &amp;\color{red}{13}\\
\end{array}$$
  
  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?


Since I am a beginner, I am looking for suggestions for improving the efficiency of my program.

from timeit import default_timer as timer
start = timer()
def find_sum(limit):
    limit*=limit
    num=1
    add=2
    result=1
    while num&lt;limit:
        for i in range(4):
            num+=add
            result+=num
        add+=2
    return result
print (find_sum(1001))
elapsed_time = (timer() - start) * 1000 # s --&gt; ms
print ("Found in %r ms." % (elapsed_time))
An ultimate efficiency is in math. It can be shown that the result for \$2n+1\$ by \$2n+1\$ spiral is

$$(\frac{2n}{3}) (8n^2 + 15n + 13) + 1$$

The formula can be derived by induction. Another method is to realize that it must be a cubic dependency and fit the coefficients. And you can see that it is cubic, because numbers along the diagonals grow quadratically.