## Project Euler Problem #60

### November 20, 2016

Read the details of the problem here

Summary

Prime pair sets.

Solution

This problem took a little bit of thinking about, primarily to get it to perform adequately – on the basis that I’m trying to get this to run in under 5 seconds. When I first solved this problem I simply couldn’t get the computational performance out of Groovy to do the prime validation quickly enough and ended up calling out to a native Java method. With the introduction of the @CompileStatic AST transformation this has made it possible to do. After my next laptop upgrade, I’m going to be having to aim for maybe 2 seconds at the most on these questions!

The solution uses a fairly naive implementation of an isPrime() method which is still substantially faster than using BigInteger#isProbablePrime() from Groovy when using @CompileStatic – at least for the range of numbers being used here. I made an assumption that 4-digit primes would be sufficient to solve this question and, luckily, it worked out to be correct.

The program starts by constructing a list of primes mapped to a list of other primes that conform to the question’s constraints of both orders of concatenation also being prime. Using lists of strings rather than integers saves a lot of overhead in the subsequent checks. The lists only contain primes that are greater than the key. So, for example, 3’s list contains 7 (as both 37 and 73 are prime), but that of 7 doesn’t contain 3. Any numbers that have fewer than 4 entries in their list are dropped as a set of 5 primes are being sought. The lowest number in that set will have the full membership in it’s list.

Having generated this list of prime-pairs, a set of primes are grown to find a five members set that fulfil the criteria. At each recursion the entries of the list of the most recently added member are checked to make sure that they meet the concatenation criteria of each of the other member of the list (by making sure that it’s on their respective lists of potential pairs) and that it wouldn’t exceed the current minimum value found. For each of the values that fulfil this criteria, a recursion is called with this appended to the current list. The minimum value found for that particular path is returned. In this respect it’s like creating a directed graph with the nodes (of which there are only 1,227) being the primes and the edges (of which there are 17,845) being the fact that two nodes fulfil the concatenation criteria.

There are probably some algorithmic optimisations that could be made here but, as it is, the code is quite simple to understand.

```import groovy.transform.CompileStatic

@CompileStatic
boolean isPrime(final int num) {

if (num <= 1) return false
if (num <= 3) return true
if ((num % 2 == 0) || (num % 3 == 0)) return false

int r = (int)Math.sqrt(num)
int f = 5

while (f <= r) {
if (num % f == 0) return false
if (num % (f + 2) == 0) return false
f += 6
}

true
}

def getPrimePairs(maxnum) {

def primes = ((2..maxnum).findAll { isPrime(it) })*.toString()
def primeCount = primes.size()
def pairs = [:]

for (ip1 in 0..<primeCount - 1) {
def sp1 = primes[ip1]
pairs[sp1] = [] as Set
for (ip2 in (ip1 + 1)..<primeCount) {
def sp2 = primes[ip2]
if (isPrime((sp1 + sp2).toInteger()) &&
isPrime((sp2 + sp1).toInteger())) {
pairs[sp1] << sp2
}
}
if (pairs[sp1].size() < 4) pairs.remove(sp1)
}
pairs
}

def find5(list, min, pairs) {

def sum = list*.toInteger().sum()
if (list.size() == 5) return sum

pairs[list[-1]].findAll { p -> ((sum + p.toInteger()) < min) &&
(list.every { pairs[it].contains(p) }) }
.each { min = [ min, find5(list + it, min, pairs) ].min() }
min
}

def (answer, primePairs) = [ Integer.MAX_VALUE, getPrimePairs(10000) ]

for (p in primePairs.keySet()) {
}
```

This executes in Groovy 2.4.7 under Java 8u112 in around 2.9 seconds, so within my 5 second cut-off. The build of the list of primes takes about 115 ms, with the construction of the prime pair map taking another 1.5 seconds. The isPrime() method is called around 850,000 times and takes around 960 ms of the total runtime.

Conclusion

Quite surprisingly, Groovy was perfectly good for this problem as long as @CompileStatic is used to optimise the isPrime() method. Left as dynamic, the runtime pushes out to just under 30 seconds. The Groovy listops made it easy to construct the prime-pair lists and for quite an expressive statement for the recursive descent conditions.

## Project Euler Problem #54

### November 18, 2016

Read the details of the problem here

Summary

Poker hands.

Solution

This was a straightforward programming problem rather than anything taxing from a mathematical perspective. I used Groovy listops to process the input file into a sorted list of [ count, face_value ] pairs that could then just be inspected in order of priority (along with some flags to indicate whether there was a monotonic sequence and a only a single suit in the hand) to rank the hand.

There are only 5 combinations of counts available (as given below). It would have been possible to simply check against these to provide a basic classification of the hand but with the need to have the flush and straight processing it just seemed easier and clearer to have the ranking done explicitly.

Count Permutations: [ 1, 1, 1, 1, 1 ], [ 2, 1, 1, 1 ], [2, 2, 1 ], [ 3, 2 ], [4, 1]

Ties were broken by using a base-13 (tridecimal) system with the rank being the most-significant digit and then using the first two group face values as the differentiators so a simple score was created for each hand. As it happened there were no clashes that weren’t broken by this method – it would have to be extended to subsequent cards and then suits (which were ignored in this question) otherwise, so you’d end up with a base-52 (duopentagecimal) system where each card had a unique value but were grouped unless there were clashes.

It didn’t take a lot of coding to get this done. It could be done more tersely, perhaps, but it would be more cryptic!

```class Hand {

private final _cards
private final _isStraight
private final _isFlush

Hand(cardList) {
def vals = cardList.collect { ['face': '23456789TJQKA'.indexOf(it[0]), 'suit': it[1]] }

_isFlush = (vals.groupBy { it.suit }.size() == 1 )
_cards   = vals.groupBy { it.face }
.collect { [ (it.value.size), it.key ] }
.sort { -(it[0] * 13 + it[1]) }
_isStraight = (_cards.size() == 5) && (_cards[0][1] - _cards[-1][1] == 4)
}

def score() {
rank() * 169 + _cards[0][1] * 13 + _cards[1][1]
}

def rank() {
if (_isStraight && _isFlush && _cards[0][1] == 12) return 9
if (_isStraight && _isFlush)                       return 8
if (_cards[0][0] == 4 )                            return 7
if (_cards[0][0] == 3 && _cards[1][0] == 2 )       return 6
if (_isFlush)                                      return 5
if (_isStraight)                                   return 4
if (_cards[0][0] == 3 )                            return 3
if (_cards[0][0] == 2 && _cards[1][0] == 2 )       return 2
if (_cards[0][0] == 2)                             return 1
0
}

def beats(opponent) {
def (s1, s2) = [ this.score(), opponent.score() ]
if (s1 > s2) return true
assert (s1 != s2)
}
}

def cards = it.split(" ")
new Hand(cards[0..4]).beats(new Hand(cards[5..-1]))
}
```

This executes in Groovy 2.4.7 under Java 8u112 in around 0.25 seconds, so well within my 5 second cut-off.

Conclusion

Groovy was perfectly good for this problem with the simple file handling and listops allowing the input to be prepared for processing very easily.

## Project Euler Problem #144

### April 1, 2013

Read the details of the problem here

Summary

Investigating multiple reflections of a laser beam.

Solution

A nice little problem and really helped by Euler providing the slope tangent for points on the ellipse. It’s a matter of finding the intersection point between the vector denoting the beam’s path and the ellipse equation and then reflecting it around the normal (at right angles to the tangent) of the mirror’s slope at that point (using the dot and cross products). This just repeated until the beam intersection is within a suitable tolerance of the entry/exit gap at the top.

```def ( answer, epsilon ) = [ 0, 0.01d ]

def p0 = [ x:0.0d, y:10.1d ]
def p1 = [ x:1.4d, y:-9.6d ]

!((Math.abs(p1.x) <= epsilon && (p1.y > 0.0)))) {

def a = [ x:p0.x - p1.x, y:p0.y - p1.y ]
def b = [ x:-4.0 * p1.x, y:-p1.y]

def ( dotp, crossp ) = [  a.x * b.x + a.y * b.y,
a.x * b.y - b.x * a.y ]

def c = [ x: dotp * b.x - crossp * b.y,
y: crossp * b.x + dotp * b.y ]
def s = (-2.0 * (4.0 * c.x * p1.x + c.y * p1.y)) /
(4.0 * (c.x * c.x) + (c.y * c.y))
def p2 = [ x:s * c.x + p1.x, y:s * c.y + p1.y ]

( p0, p1 ) = [ p1, p2 ]
}

```

This executes in Groovy 1.8.8 under Java 7u17 in around 0.12 seconds, so well within my 5 second cut-off.

Conclusion

Groovy made for quite a terse solution to this problem. The ability to use tuples with named members as lightweight point and vector classes was quite convenient and made for more readable code. The multiple assignment capability kept the LoC count down too. It’s important to include the ’d’ type signifiers on the starting values to force the use of doubles throughout the calculations. This is one of those Gr-r-r-oovy annoyances that I’d prefer not having to worry about though.

## Project Euler Problem #64

### March 4, 2012

Read the details of the problem here

Summary

How many continued fractions for N ≤ 10000 have an odd period?

Solution

It took a little while for me to understand how this was working so, to make it clearer this is essentially what’s required.

1. Take the square root of the original number then…
2. The integer portion becomes the next number in the sequence,
3. Take the reciprocal of the remaining decimal portion,
4. Take this number as input into Step 2.

Obviously, at step 3, if the decimal portion has been seen before, that sequence would just repeat from then on, so a cycle would have been found. In that respect it’s very similar to the solution for Problem #26.

As an example, here’s the trace for 23, with it’s square root – 4.79583.

n Digit Remainder
4.79583 4 0.79583
1.25655 1 0.25655
3.89792 3 0.89792
1.11369 1 0.11369
8.79583 8 0.79583
1.25655 1 0.25655

Whilst this works as an implemented algorithm for numbers with short sequences it breaks down on the longer ones, some of which are over 200 elements long, due to problems with precision. So I expanded out the algorithm to better reflect the way that Euler describes in the question and coded that up. I made the assumption that the sequence would start from the first position rather than an arbitrary one.

```def cf(n) {
def ( i, j, c, k ) = [ 0, 1, 0, null ]
def sqrt_n = Math.sqrt(n)
while (true) {
j = (n - (i * i)).intdiv(j)
i = -(i - ((int)(sqrt_n + i)).intdiv(j) * j)
if ([i, j] == k) return c - 1
if (c == 1) k = [i, j]
c++
}
}

(((int)Math.sqrt(it)) ** 2 != it) && (cf(it) % 2)
}
```

This executes in Groovy 1.8.6 under Java 7u3 on my Samsung 700G7A i7-2670QM 2.2 GHz machine in around 0.45 seconds, so well within my 5 second cut-off (reduced from the old 15 seconds on my old machine). This runs quite fast as it only ever uses integers – apart from the initial sqrt calculation.

Conclusion

Didn’t use many Groovy features for this solution in the main apart from keeping the function initialization quite terse and the count listop on the number range. Performance was fairly good – though an equivalent Java solution does run in 55 ms – around 8 times faster.

## Project Euler Problem #243

### January 21, 2012

Read the details of the problem here

Summary

Find the smallest denominator d, having a resilience R(d) < 15499 ⁄ 94744

Solution

Due to real-life intrusion I haven’t been doing much Project Euler for the last few months but a conversation with a colleague at work the other day brought the subject up and I thought I’d revisit the site.

They’ve changed their format quite a lot now and though it’s still fundamentally the same, the concept of “badges” has been introduced – “awards” above and beyond just the old numbers of puzzles solved (which is now more granular). I’m a sucker for things like that and one of them – “Trinary Triumph” – just needed one more question to complete so it was, as the saying goes, like a red rag to a bull!

The problem was actually worded quite straightforwardly, and a little thought showed that this was very similar to Problem #69 and Problem #70. The numerator in the resilience function is going to be the count of terms that are relatively prime to the denominator i.e. Euler’s Totient (φ) function. The solution to Problem #69 was found by maximising n/φ(n) whereas, in this problem we’re looking to minimize φ(d)/(d-1) – so it’s essentially the same thing. The answer is likely to be found by looking for a number consisting of the product of many small prime factors perhaps with some multiplier (also a product of small primes) i.e. some of those factors may be of a higher power.

Problem #108 and Problem #110 also tackled the domain of products of powers of primes and the solution to the latter seemed a good place to start as the one to the former ended up as being a bit of a lucky hack. As per that solution, taking the approach of assuming that the answer was to be found somewhere at n * product(prime factors) and driving off that meant that factorisation of large numbers wasn’t needed so Groovy would remain a viable language to do this in.

Again, when doing these problems with Groovy, it’s best to try to work out the potential scope ahead of runtime as it doesn’t perform that well at number crunching.

What I did need to how to calculate the totient value for numbers with large numbers of factors – I’d kind of worked it out from a bit of guess work for two factors when doing Problem #70 but this wouldn’t work for this. Luckily Wikipedia came to the rescue giving the formula quite succinctly as:

φ(n) = n(1-1/p1)(1-1/p2)…(1-1/pr).

Using this I found that the product of a prime sequence 2..23 gave a totient above what was being sought, whilst 2..29 was a potential solution itself. The answer probably fell somewhere between these two and this therefore formed the search space.

I then just reused the helper function I’d used in Problem #110 with a bit of an educated guess as to what the maximum power might be. If the multipler was 25 i.e. 32, this would exceed the solution of the longer prime sequence – so a maximum power of 4 seemed reasonable to use. I also seeded the generator function with the assumption that all of the primes between 2..23 were going to be factors – this seemed a reasonable assumption given what I knew of the totient function characteristics.

```def gen_powers(range, maxlen, yield) {
gen_powers(range, maxlen, [], yield)
}

def gen_powers(range, maxlen, pows, yield) {
if (pows.size() == maxlen)
yield(pows)
else if (pows.size() == 0)
range.each { gen_powers(range, maxlen, [it], yield) }
else
range.findAll { it >= pows[0] }
.each { gen_powers(range, maxlen, [it]+pows, yield) }
}

def ( answer, TARGET, POWER_RANGE ) = [ Long.MAX_VALUE, 15499/94744, (0..4) ]
def primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ]

gen_powers(POWER_RANGE, primes.size(), [1] * primes.size()- 1) { powers ->
def (d, factors) = [ 1G, [] ]
powers.eachWithIndex { v, i ->
d *= primes[i] ** v
if (v > 0) factors << primes[i]
}
if ((d > 1) &&
(((int)(factors.inject(d) { p, v -> p * (1 - 1/v) })) / (d-1) < TARGET)) {
}
}
```

Despite the heavy use of the slow Groovy listops (and a bit of hacky code) this runs in around 940 ms.

Next will be Problem #65, a question on continued fractions, that will give me my “As Easy As Pi” award!

Conclusion

With the upfront analysis on the problem and the re-use of the power generator, Groovy made it easy to put together a terse solution that ran in a reasonable time. When doing the calculation of the value of the denominator I did find myself missing Python’s map() capability to process two lists against a closure and return a result. Sounds like the sort of thing that should be in there, maybe it’s buried in the Groovy docs somewhere…

## 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 ]

( ((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 ]

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.

## Project Euler Problem #39

### April 30, 2010

Read the details of the problem here

Summary

If p is the perimeter of a right angle triangle, {a, b, c}, which value, for p ≤ 1000, has the most solutions?

Solution

Straightforward, brute-force solution. Just run through a combination of lengths for two sides and calculate the hypotenuse. For hypotenuses that are of integer length, check that the perimeter is within the limit set and, if so, increment a count for that length keeping track of the maximum element as it goes along.

```def LIMIT = 1000
def ( c, max, answer ) = [ [0]*LIMIT, 0, 0 ]

for (i in 1..<LIMIT.intdiv(2)) {
for (j in 1..<LIMIT-i) {
def hyp = ((i * i) + (j * j)) ** 0.5
if ((int)hyp == hyp) {
def p = i + j + hyp
if (p < LIMIT) {
c[p]++
if (c[p] > max) ( max, answer ) = [ c[p], p ]
}
}
}
}
```

This runs in 0.59 seconds.

Conclusion

Groovy made for a terse syntax but nothing that couldn’t have easily been done in Java. Interestingly, replacing the pythonic syntax of the square root (n ** 0.5) with the traditional Java library call to Math.sqrt(n) the run-time drops to 0.27 seconds. In this case p needs to be forced to an int when being used as an index into c[]. This change in performance is quite astonishing.