Sunday Times Teaser 2711 – Megan’s House
by Graham Smithers
The students in Megan’s class were each asked to use eight of the nine digits 1 .. 9 to produce three two digit squares and a two digit prime, thus leaving one digit unused.
If you knew Megan’s house number, which was the same as her unused digit, you would then be able to work out her four numbers.
What were they?
One Comment
Leave one →
-
brian gladman permalink1234567891011121314151617181920212223242526272829from itertools import combinationsfrom collections import defaultdict# list of two digit squaressq = [str(x * x) for x in range(4, 10)]# list of two digit primes with no repeated digitspr = [str(x) for x in range(13, 100, 2) if all(x % p for p in (2, 3, 5, 7))]# dictionary for mapping house numbers to possible sets of four numbersd = defaultdict(list)# combine three squaresfor n3 in combinations(sq, 3):# find three squares that leave three of the digits 1..9 unusedrem = set('123456789') - set(''.join(n3))if len(rem) == 3:# now find a prime that uses only (two of) the remaining digitsfor p in pr:if set(p) < rem:# separate the house number (the unused digit)house, = rem - set(p)# add the four numbers to our list for this house numberd[house].append(tuple(sorted(n3 + (p,))))# find a house number with only one possible set of four numbersfor k, v in d.items():if len(v) == 1:print("Megan's numbers were {}, {}, {} and {}.".format(*v[0]))