Project Euler Problem #52
April 30, 2010
Read the details of the problem here
Summary
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits in some order.
Solution
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
i++
}
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
}
i++
}
So that’s the two-for-one deal on this solution.
Conclusion
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.

May 26, 2010 at 14:20
[...] 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 [...]