# Enigmatic Code

Programming Enigma Puzzles

From New Scientist #2344, 25th May 2002 [link]

I was playing about with my seven-digit-display calculator, showing my numerate nephew a trick or two. I displayed a number on the calculator and he looked at it upside down. After some jottings of his own he declared “I can see a number too, and it’s a perfect square”.

I then doubled my original number and displayed the answer and again he looked at it upside down and did some calculations.

“I can still see a number, and it’s another perfect square”, he said.

Which number did I originally display?

[enigma1188]

### One response to “Enigma 1188: Square roundabout”

1. Jim Randell 21 December 2015 at 8:34 am

This Python program runs in 53ms.

```from itertools import count
from enigma import is_square, join, irange, printf

# numbers which read as numbers when inverted on a 7-segment display
inverted = { '0': '0', '1': '1', '2': '2', '5': '5', '6': '9', '8': '8', '9': '6' }

# invert a number (passed as a decimal string)
def invert(n):
try:
s = join(inverted[x] for x in reversed(n))
except KeyError:
return None
i = int(s)
return (i if str(i) == s else None)

# consider increasing squares for the first inverted number
for r1 in count(1):
i1 = str(r1 * r1)
# it can't have more than 7 digits
if len(i1) > 7: break
# invert it to get the original number
n1 = invert(i1)
if n1 is None: continue
# double the original number
n2 = str(n1 * 2)
if len(n2) > 7: continue
# and invert it
i2 = invert(n2)
if i2 is None: continue
# that should also be a square
r2 = is_square(i2)
if r2 is None: continue

printf("first number = {n1}, inverted = {i1} ({r1}^2), second number = {n2}, inverted = {i2} ({r2}^2)")
```

Solution: The original number was 9126 (the correct way up).

9126 reads as 9216 (= 96²) when inverted.

9126 doubled is 18252, which reads as 25281 (= 159²) when inverted.

We ignore the trivial solution where all numbers are 0, because there is some calculation involved to determine if a number is a perfect square.