Project Euler Problem #52

April 30, 2010

Read the details of the problem here


Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits in some order.


I used Groovy listops to drive this in, in essence, a single line within a loop. It was quick to write and “obviously correct” but very slow – taking 2.82 seconds. Using as Set is faster than using groupBy() to eliminate duplicates.

def ( i, answer ) = [ 1, 0 ]

while (answer == 0) {

  answer =
      ( ((1..6).collect { (i * it).toString().toList().sort() } as Set)
               .size() == 1 ) ? i : 0


Removing the reliance on the list operators, as per the solution below, brings the runtime down to 0.78 seconds. The code isn’t really any more complex.

def ( i, answer ) = [ 1, 0 ]

while (answer == 0) {

  def s = (i.toString() as List).sort()

  for (j in 2..6) {
    if (s != (i * j).toString().toList().sort()) break
    if (j == 6) answer = i


So that’s the two-for-one deal on this solution.


Groovy – You can take declarative logic, or some moderate performance. Take your pick.

Note: Putting this performance into context though, a port of the solutions to Ruby 1.8.7 has them running in 20.2 seconds and 4.55 seconds respectively. Running these scripts in JRuby 1.5.0 gives run times of 5.57 seconds and 1.60 seconds respectively. So both Groovy and the JVM scores very well in this regard.


One Response to “Project Euler Problem #52”

  1. […] selected the solutions for Problem #52 and converted them over to the other languages. I also tried the Ruby solution in JRuby in the same […]

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: