Project Euler Problem #28

February 14, 2010

Read the details of the problem here


What is the sum of both diagonals in a 1001 by 1001 spiral?


Another straightforward problem. The sum of the corners of a ring is quite simple and it’s just a case of spotting the increment that the bottom right-hand corner undergoes as the spiral expands.

def ( answer, brval ) = [ 1, 3 ]

(1..500).each { ring ->
  answer += 4 * brval + 6 * (2 * ring)
  brval += 8 * ring + 2

Note that the answer (sum of numbers) starts at 1 as ring 0 is a special case having only one element and isn’t handled in the loop.

This runs in 0.47 seconds. A Java version using longs runs in around 0.28 ms – more than 1500x faster. Jeepers.


I didn’t really use any specific Groovy feature here apart from multiple assignment in a few places and in the loop syntax. Performance was completely adequate for the scope of this problem but still dismally slow compared to Java for this type of work.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: