# Enigmatic Code

Programming Enigma Puzzles

## Enigma 204: Three mental ages

From New Scientist #1350, 24th March 1983 [link]

Every Christmas I assemble my three nephews and ask each to state his mental age, which must be an exact whole number of years not greater than 100. Then I give to each, for every year of his stated age, as many pounds as he says he is years old.

Both last year and this year I noticed that my total outlay could be more simply calculated by just multiplying the three ages together.

Last year all three claimed the same age. This year the three ages were all different, and none was the same as last year’s.

Can you tell me last year’s and this year’s trios of ages? The answers, I believe, are unique. Trial and error will be shortened once you notice that if (A, B, C) is a possible trio of ages, so is …

[enigma204]

### 2 responses to “Enigma 204: Three mental ages”

1. Jim Randell 5 July 2014 at 8:24 am

This Python program runs in 104ms.

from itertools import combinations
from enigma import irange, printf

ages = set(irange(1, 100))

# last year they each chose a common mental age, m
# so to each nephew I gave m * m,
# so in total I gave 3 * m * m
# and this is the same as the product of the ages
# 3 * m * m = m * m * m
# so m = 3

m = 3

# this year they chose different ages (and none of them m)
# p * p + q * q + r * r = p * q * r

for (p, q, r) in combinations(ages.difference([m]), 3):
if p * p + q * q + r * r == p * q * r:
printf("last year: {m}, {m}, {m}; this year: {p}, {q}, {r}")

Solution: Last years stated ages were 3, 3, 3; This years stated ages were 6, 15, 87.

The problem reduces to finding (p, q, r) such that p² + q² + r² = p×q×r, with numbers from 1 to 100.

There are five triples:

(3, 3, 3)
(3, 3, 6)
(3, 6, 15)
(3, 15, 39)
(6, 15, 87)

The only triple with all the numbers the same is (3, 3, 3), and the only triple that doesn’t include 3 is (6, 15, 87).

• Jim Randell 5 July 2014 at 9:14 am

Here’s another version that considers fewer combinations. Supposing p < q < r, it considers pairs of values for p and q, and then looks for solutions of the quadratic equation:

p² + q² + r² = pqr
⇒ r² + (-pq)r + (p² + q²) = 0

It runs in 47ms.

from itertools import combinations
from enigma import irange, is_square

ages = set(irange(1, 100))

m = 3

for (p, q) in combinations(ages.difference([m]), 2):
(b, c) = (-p * q, p * p + q * q)
s = b * b - 4 * c
if s < 0: continue
s = is_square(s)
if s is None: continue
for t in (s, -s):
(r, x) = divmod(t - b, 2)
if x == 0 and r != m and q < r < 101:
print((p, q, r))