Enigmatic Code

Programming Enigma Puzzles

Enigma 1638: Same five digits

From New Scientist #2804, 19th March 2011 [link]

I have written down three different 5-digit perfect squares, which between them use five different digits. Each of the five digits is used a different number of times, the five numbers of times being the same as the five digits of the perfect squares. No digit is used its own number of times. If you knew which digit I have used just once you could deduce my three squares with certainty.

What are my three perfect squares?



One response to “Enigma 1638: Same five digits

  1. jimrandell 11 December 2011 at 4:49 pm

    The following Python program executes in 35ms.

    from itertools import combinations
    from collections import defaultdict
    # it is apparent that the digits used are 1..5 as there are 15 digits all
    # together and 1+2+3+4+5 is the only way to make 15 out of 5 digits
    sdigits = set("12345")
    # find the 5-digit squares compose of the digits 1..5
    squares = list()
    for i in range(100, 316):
      n = i * i
      if not set(list(str(n))).issubset(sdigits): continue
    def check(digits):
      if 1 not in digits: return False
      if len(digits.keys()) != 5: return False
      if len(set(digits.values())) != 5: return False
      if set(digits.keys()) != set(digits.values()): return False
      for (k, v) in digits.items():
        if k == v: return False
      return True
    # record the solutions according to the digit that is used only once
    solutions = dict((x, []) for x in range(0, 10))
    for s in combinations(squares, 3):
      digits = defaultdict(int)
      for i in s:
        for d in list(str(i)):
          digits[int(d)] += 1
      if not check(digits): continue
      print(s, dict(digits))
      rev = dict((v, k) for k, v in digits.items())
      solutions[rev[1]].append((s, digits))
    for v in solutions.values():
      if len(v) != 1: continue
      print(v[0][0], dict(v[0][1]))

    Solution: The three squares are 12321, 33124 and 34225.

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: