Updates from April, 2023 Toggle Comment Threads | Keyboard Shortcuts

  • Unknown's avatar

    Jim Randell 11:57 am on 23 April 2023 Permalink | Reply
    Tags:   

    Brain teaser 1005: Words and numbers 

    From The Sunday Times, 1st November 1981 [link]

    A familiar letters-for-digits problem is to take a correct addition sum such as:

    1 + 1 = 2

    and write it in words so:

    ONE + ONE = TWO

    The problem is to assign numbers from 0 to 9 to the letters so that we get a correct addition sum, e.g. E = 6, N = 3, O = 2, T = 4, W = 7 gives:

    236 + 236 = 472

    Two rules to be kept are that the left hand digit of any number is not zero, and different letters are assigned different numbers.

    Some addition sums clearly have no solution. e.g.:

    ONE + THREE = FOUR

    In the Kudali Language the words for 1, 2, 3, 4 are AA, BA, EB, DE, although not necessarily in that order. Now all the addition sums:

    1 + 1 = 2
    1 + 2 = 3
    1 + 3 = 4
    2 + 2 = 4
    1 + 4 = 2 + 3

    when written in Kudali, give letters-for-digits problems each of which has at least one solution.

    What are the Kudali words for 1, 2, 3, 4, in that order?

    This puzzle is included in the books Microteasers (1986) and The Sunday Times Book of Brainteasers (1994).

    [teaser1005]

     
    • Jim Randell's avatar

      Jim Randell 11:57 am on 23 April 2023 Permalink | Reply

      This Python program uses the [[ SubstitutedExpression() ]] solver from the enigma.py library to see if there are solutions to the alphametic expressions.

      It runs in 85ms.

      Run: [ @replit ]

      from enigma import (SubstitutedExpression, subsets, sprintf, printf)
      
      # does an alphametic sum have answers?
      solve = lambda expr: any(SubstitutedExpression([expr]).solve(verbose=0))
      
      # expressions involving words for 1, 2, 3, 4
      exprs = [
        "{w1} + {w1} = {w2}",
        "{w1} + {w2} = {w3}",
        "{w1} + {w3} = {w4}",
        "{w2} + {w2} = {w4}",
        "{w1} + {w4} == {w2} + {w3}",
      ]
      
      # allocate the words
      for (w1, w2, w3, w4) in subsets(["AA", "BA", "EB", "DE"], size=4, select='P'):
        # are all the expressions solvable?
        if all(solve(sprintf(x)) for x in exprs):
          # output solution
          printf("1 = {w1}; 2 = {w2}; 3 = {w3}; 4 = {w4}")
      

      Solution: 1 = DE; 2 = BA; 3 = AA; 4 = EB.

      So we have:

      DE + DE = BA → 13 + 13 = 26, …
      DE + BA = AA → 10 + 23 = 33, …
      DE + AA = EB → 13 + 22 = 35, …
      BA + BA = EB → 21 + 21 = 42, …
      DE + EB = BA + AA → 14 + 42 = 23 + 33, …

      Like

    • Frits's avatar

      Frits 5:10 pm on 23 April 2023 Permalink | Reply

       
      from enigma import subsets
      
      '''
      0: ab + ab = ef       reject if: b in {a, f}, e = f,
      1: ab + cd = ef       reject if: b = f and d in {a, e}, d = f and b in {c, e}
                                       e = f and (b = c or a = d)
      2: ab + cd = ef + gh  reject if not: b = d or f = h 
      '''
      
      # reject words depending on the type of equation
      def rej(t, w, x, y, z=0):
        (a, b) = (w[0], w[1])
        (c, d) = (x[0], x[1])
        (e, f) = (y[0], y[1])
        if t == 0 and (e == f or b in {a, f}): return True
        if t == 1 and any([b == f and d in {a, e}, d == f and b in {c, e},
                           e == f and (b == c or a == d)]): return True
        if t == 2 and not (b == d or f == z[1]): return True                   
        
        return False
      
      # allocate the words
      for (w1, w2, w3, w4) in subsets(["AA", "BA", "EB", "DE"], size=4, select='P'):
        if rej(0, w1, w1, w2): continue
        if rej(1, w1, w2, w3): continue
        if rej(1, w1, w3, w4): continue
        if rej(0, w2, w2, w4): continue
        if rej(2, w1, w4, w2, w3): continue
        print(*zip(range(1, 5), (w1, w2, w3, w4)))
      

      Like

      • Frits's avatar

        Frits 5:23 pm on 23 April 2023 Permalink | Reply

        This is more of a program saying: “if there is a solution it must be one of these: ….”

        Like

  • Unknown's avatar

    Jim Randell 9:09 am on 16 April 2023 Permalink | Reply
    Tags: by: R J Webster   

    Brain teaser 977: Little boy blue 

    From The Sunday Times, 12th April 1981 [link]

    The baby department of our local store has just organised a raffle. The tickets were numbered consecutively from one upwards and were made into large books, each containing the same number of consecutive tickets.

    Numbers having at least one repeated digit were printed on blue paper and those having all their digits different were printed on pink paper. It turned out that there was an equal number of blue and pink tickets. The prize was a generously equipped layette in the colour of the winning ticket.

    Being the first person to buy a ticket, I had the opportunity to see that among the large collection of books only one of them consisted of tickets all of the same colour, and it was the colour I wanted too.

    Spoilt for choice, I bought the ticket in the middle of this book. My choice was fully justified: I won the prize!

    What was my winning number?

    The version of the puzzle published in the book Microteasers (1986), also includes the additional question:

    How many tickets were there?

    The puzzle is also included in the book The Sunday Times Book of Brainteasers (1994).

    [teaser977]

     
    • Jim Randell's avatar

      Jim Randell 9:09 am on 16 April 2023 Permalink | Reply

      This Python program runs in 72ms. (Internal runtime is 13.0ms).

      Run: [ @replit ]

      from enigma import (
        irange, inf, is_duplicate, divisors_pairs,
        seq_all_same, singleton, printf
      )
      
      blue = pink = 0
      ts = [None] # there is no ticket 0
      
      # look for books with tickets the same colour
      def same_colour(ts, n, k):
        for i in irange(1, n, step=k):
          if seq_all_same(ts[i] for i in irange(i, i + k - 1)):
            yield i
      
      # consider number of tickets
      for n in irange(1, inf):
        f = is_duplicate(n)
        ts.append(f)
        if f:
          blue += 1
        else:
          pink += 1
      
        if blue == pink:
          printf("total={n} [blue={blue} pink={pink}]")
      
          # consider j books, each with k tickets
          done = 0
          for (j, k) in divisors_pairs(n, every=1):
            # k is odd (and  > 1)
            if not (k > 1 and k % 2 == 1): continue
            # find books with tickets all the same colour
            b = singleton(same_colour(ts, n, k))
            if b is None: continue
            printf("-> {j} books, each with {k} tickets -> {b} .. {x}", x=b + k - 1)
            if k % 2 == 1:
              # find the middle ticket
              t = b + (k // 2)
              printf("-> middle ticket = {t}")
              done += 1
      
          if done: break
      

      Solution: The winning number was: 10073.

      There were 44 books, each with 255 tickets, making 11220 tickets in total. 5610 of them are blue, and 5610 of them are pink.

      The book of tickets from 9946 – 10200 consists of 255 tickets, all of which have repeated digits, so are coloured blue.

      The ticket in the middle of this book is 10073 (there are 127 tickets before it and 127 tickets after it).

      Like

    • Hugo's avatar

      Hugo 10:48 am on 16 April 2023 Permalink | Reply

      Is it possible that there were 187 tickets per book? In that case there would be a book 9912 – 10098,
      with middle number 10005. If it had been fewer than 187, there would be two all-blue books.

      I think the longest possible run with repeated digits is 357, from 9877 to 10233.

      Like

      • Frits's avatar

        Frits 11:28 am on 16 April 2023 Permalink | Reply

        @Hugo, as 187 is less than 220 (there are 11220 tickets in total) the last book must be all-blue as well (all tickets of the form 11xxx).

        Like

  • Unknown's avatar

    Jim Randell 9:26 am on 2 April 2023 Permalink | Reply
    Tags: by: V. Bryant   

    Brainteaser 1099: Jackpot! 

    From The Sunday Times, 28th August 1983 [link]

    Our local maths club has an appropriate slot machine. It consists of the digits from 1 to 9 in a row and each of them has a star below it which can light up. The machine always has some of the stars lit up and the idea is to read the number formed by the lit-up digits. So, for example, in the situation illustrated the number is 14689.

    There are four possible jackpots which this machine pays out. To have a go you observe the lit-up number, place 10p in the slot (which causes a different selection of digits to light), and observe the new number. (The machine is then ready for the next go). The jackpots are the “Fair Share” which is won if the number showing after putting in your 10p is precisely half the number which was showing before. The “Rare Square” which is won if the number showing after putting in your 10p is the square of the number showing before. The “Cute Root” which requires that the number before you place in the 10p is the square of the number showing afterwards. And the “Rum Sum” which is won if the number showing after you place in your 10p is the sum of the digit which were lit up before.

    One member had a very successful session yesterday. He placed four 10ps in the machine in order to have  four consecutive goes. And the sequence of five different selections of lit-up digits which he observed resulted in him winning all four jackpots.

    What number was showing immediately before he put in his first 10p?

    This puzzle is included in the book Microteasers (1986).

    [teaser1099]

     
    • Jim Randell's avatar

      Jim Randell 9:26 am on 2 April 2023 Permalink | Reply

      In order to arrive at a unique solution I had to (reasonably) assume that “some of the stars” means “at least 2 of the stars”.

      This Python program runs in 63ms. (Internal runtime is 7.8ms).

      Run: [ @replit ]

      from enigma import (irange, subsets, nconcat, dsum, diff, printf)
      
      # possible displayed numbers
      # = numbers with at least 2 different digits in increasing order
      ns = list(subsets(irange(1, 9), min_size=2, fn=nconcat))
      
      # record prize pairs
      prize = { 1: set(), 2: set(), 3: set(), 4: set() }
      
      # collect prize numbers
      for n in ns:
        tw = 2 * n
        if tw in ns:
          prize[1].add((tw, n))
        sq = n * n
        if sq in ns:
          prize[2].add((n, sq))
          prize[3].add((sq, n))
        ds = dsum(n)
        if ds in ns:
          prize[4].add((n, ds))
      
      # find a sequence of numbers that give prizes in <ks>
      def solve(ks, ss):
        if not ks:
          yield ss
        else:
          x = ss[-1]
          for k in ks:
            for (y, z) in prize[k]:
              if x == y and z not in ss:
                yield from solve(diff(ks, {k}), ss + [z])
      
      # choose a starting pair
      for (k, vs) in prize.items():
        for (a, b) in vs:
          # solve for the remaining prizes
          for ss in solve(diff(prize.keys(), {k}), [a, b]):
            printf("{ss}")
      

      Solution: The machine was initially showing: 134689.

      So we have:

      134689 -(sqrt)-> 367 -(dsum)-> 16 -(sq)-> 256 -(half)-> 128

      Like

    • Frits's avatar

      Frits 6:35 pm on 2 April 2023 Permalink | Reply

      Starting from Jim’s program but not using enigma.py and using a dictionary of slot machine numbers .

         
      from itertools import combinations
      
      dsum = lambda n: sum(int(x) for x in str(n))
      
      # number of different selections of lit-up digits
      N = 5
       
      # possible slot machine numbers
      ns = list(int("".join(str(y) for y in x)) 
                for n in range(2, 10) for x in combinations(range(1, 10), n))
       
      # dictionary of slot machine numbers and following jackpots
      d = {n : list([0] * (N - 1)) for n in ns}
       
      # collect dictionary elements
      for n in ns:
        tw = 2 * n
        if tw in ns:
          d[tw][0] = n
        sq = n * n
        if sq in ns:
          d[n][1] = sq
          d[sq][2] = n
        ds = dsum(n)
        if ds in ns:
          d[n][3] = ds
       
      # only keep slot machine numbers after which a jackpot may occur  
      d = {k: v for k, v in d.items() if v != [0] * (N - 1)}    
      
      # find a sequence of N slot machine numbers with N - 1 different jackpots
      def solve(k, ss, types=[]):
        if len(ss) == N:
          yield ss
        else:
          for t, v in enumerate(d[k]):
            # type of jackpot already processed?
            if t in types: continue 
            if ((len(ss) == N - 1 and v in ns) or v in d):
              # number may not have been used before
              if v not in ss: 
                yield from solve(v, ss + [v], types + [t])
       
      # check slot machine numbers after which a jackpot may occur 
      for k in d.keys():
        # check if N - 1 different jackpots can follow
        for ss in solve(k, [k]):
          print(f"{ss}")
      

      Like

  • Unknown's avatar

    Jim Randell 2:16 pm on 26 March 2023 Permalink | Reply
    Tags: by: J. G. Pratt   

    Brainteaser 1159: Number unobtainable 

    From The Sunday Times, 18th November 1984 [link]

    Our little village is furious because they have ‘improved’ our telephones. In other words they closed our local exchange, added several extra non-zero figures to the beginning of each person’s old number, and then put us into Hogglestock’s exchange. We used to have only a few figures in each of our phone numbers but now with umpteen of them (more than three times as many as before) it is quite beyond me to remember any of the new ones.

    However, I thought I had found a way to work out my own number. My old one was a prime, its digits were different and they came in ascending order. The amazing thing is that those facts are true of the added figures as well, and also of the complete new number! But all the commotion has left me in such a state that I’m not sure if I can work out my number correctly.

    What is my new number?

    [teaser1159]

     
    • Jim Randell's avatar

      Jim Randell 2:17 pm on 26 March 2023 Permalink | Reply

      The digits of the phone number are in increasing order, but do not start with 0, so there can be no zeros in the entire number.

      Also the new number has more than 3× the number of digits that the old one. So the added prefix is more than twice the length of the original number.

      If the original number only has 1 digit, then the added prefix must have more than 2 (i.e. 3 or more digits).

      If the digits are all different then the final number can have no more than 9 digits, and it must be more than 3× longer than the original number, so the original number can only have 1 or 2 digits. So the prefix must have 3 – 8 digits.

      This Python program runs in 58ms. (Internal runtime is 2.1ms).

      Run: [ @replit ]

      from enigma import (irange, subsets, nconcat, is_prime, wrap, cache, printf)
      
      # generate k-length increasing numbers, that satisfy fn
      # return (<n>, <first-digit>)
      @cache
      @wrap(list)
      def generate(k, fn=is_prime):
        for ds in subsets(irange(1, 9), size=k, select='C'):
          n = nconcat(ds)
          if fn(n):
            yield (n, ds[0])
      
      # consider p-length prefix
      for p in irange(3, 8):
        for (pn, _) in generate(p):
          pd = pn % 10
          # consider s-length suffix
          for s in irange(1, (p - 1) // 2):
            for (sn, sd) in generate(s):
              if not (pd < sd): continue
              n = pn * 10**s + sn
              if not is_prime(n): continue
              # output solution
              printf("{pn} + {sn} -> {n}")
      

      Solution: The new number is: 1234789.

      The prefix is 12347, and the original number was 89.

      It doesn’t seem that hard to remember. Just dial the numbers in order, skipping 56.

      Like

    • Frits's avatar

      Frits 10:47 am on 27 March 2023 Permalink | Reply

      As we have more than three times as many figures as before and the original number had multiple digits we can conclude that the original number must have two digits (no zeroes allowed) .

      from enigma import SubstitutedExpression, is_prime
      
      # invalid digit / symbol assignments
      d2i = dict()
      for d in range(0, 10):
        vs = set()
        if d == 0: vs.update('CDEFGHI')
        # G and I must be odd
        if d % 2 == 0: vs.update('GI')
        # ABCDEFGHI is increasing
        for i in range(1, 9):
          # set maximum
          if d > i: vs.update("ABCDEFGHI"[i-1])
          # set minimum
          if d < i - 1: vs.update("ABCDEFGHI"[i])
          
        d2i[d] = vs
      
      if 0:
        print("Allowed values")
        for s in "ABCDEFGHI":   
          print(s, ":", end=" ")
          for k, vs in d2i.items():
            if s not in vs:
              print(k, end="")
          print()    
        
      def check(n):
        # n has to be a prime number
        if not is_prime(n): return False
        
        # with increasing digits
        s = str(n)
        if "".join(sorted(s)) != s: return False
        return True
      
      # the alphametic puzzle
      p = SubstitutedExpression(
        [
          "check(HI)",
          "check(ABCDEFG)",
          "check(ABCDEFGHI)",
          "A == 0 or A < B",
        ],
        answer="ABCDEFGHI",
        d2i=d2i,
        # only A and B may be the same digit (if zero)
        distinct=("ACDEFGHI", "BCDEFGHI"),
        env=dict(check=check),
        #reorder=0,
        verbose=0,    # use 256 to see the generated code
      )
      
      # print answers
      for (_, ans) in p.solve():
        print(f"my new number is {ans}")   
      

      Like

      • Jim Randell's avatar

        Jim Randell 11:40 am on 27 March 2023 Permalink | Reply

        If we accept that the suffix is 2-digits, then the prefix must 5- or 6-digits (neither 1234567 nor 123456789 is prime), so we can just consider 8-digit numbers that have an optional leading zero:

        Run: [ @replit ]

        #! python3 -m enigma -rr
        
        SubstitutedExpression
        
        # prefix is ABCDEF (A may be 0), suffix is GH
        --invalid=""
        
        # digits are increasing
        "A < B" "B < C" "C < D" "D < E" "E < F" "F < G" "G < H"
        
        # suffix, prefix and entire number are prime
        "is_prime(GH)"
        "is_prime(ABCDEF)"
        "is_prime(ABCDEFGH)"
        
        # output solution
        --answer="ABCDEFGH"
        

        Like

  • Unknown's avatar

    Jim Randell 7:46 am on 19 March 2023 Permalink | Reply
    Tags:   

    Brainteaser 1057: Palindromic primes 

    From The Sunday Times, 31st October 1982 [link]

    Teacher was introducing his class to the binary system of notation (wherein the unit values attaching to successive digits from right to left of any integer are 1, 2, 4, 8, 16, etc., as against 1, 10, 100, 1000, etc., in the decimal system).

    He went on to explain that many arithmetical relationships are equally valid in both the binary and decimal systems. And gave as the simplest example:

    10 × 11 = 110

    which in the binary system represents 2 × 3 = 6, pointing out this difference however – that while both factors 10 and 11 are primes in the binary system, only 11 is prime in the decimal system.

    Developing this theme he observed that very often such relationships could be described as “pan-palindromic”, in the sense that both of the factors, as well as their product, are numerical palindromes (i.e. each of the three integers reads the same forwards as backwards). His first example was:

    1001 × 10101 = 10111101

    (which in the binary system represents 9 × 21 = 189), and he pointed out how this time neither factor was a prime using either the binary or decimal system (being patently divisible by 11 and 3 respectively).

    He contrasted this with another example:

    111 × 1001001 = 111111111

    which in the binary system represents: 7 × 73 = 511, where both factors are primes in the binary system, but neither of them are in the decimal system (both being divisible by 3).

    To test how well his pupils were taking in all this, he told them to proceed on their own and write down any binary palindromes they could find, of less than twelve digits, which simultaneously, in both binary and decimal systems, factorised into just two different palindromic primes.

    What should they have written down?

    [teaser1057]

     
    • Jim Randell's avatar

      Jim Randell 7:47 am on 19 March 2023 Permalink | Reply

      This Python program considers numbers that are binary palindromes (with < 12 digits), and that have exactly 2 different prime factors, which are themselves binary palindromes. It then checks that if the multiplication sum is interpreted in decimal, instead of binary, that it still works, and the decimal factors are also prime.

      Total runtime is 64ms. (Internal runtime is 713µs).

      Run: [ @replit ]

      from enigma import (irange, inf, nsplit, rev, nconcat, factor, is_npalindrome, is_prime, printf)
      
      # generate numbers that are binary palindromes < 12 digits
      def generate():
        for n in irange(1, inf):
          # split n into digits
          ds = nsplit(n, base=2, fn=list)
          k = len(ds)
          if k > 6: break
          # mirror the digits to make a palindrome
          ds.extend(rev(ds))
          if k < 6: yield nconcat(ds, base=2)
          ds.pop(k)
          yield nconcat(ds, base=2)
      
      # start with a number that is a binary palindrome
      for n in generate():
        # find the prime factorisation
        fs = factor(n)
        if not (len(fs) == 2 and len(set(fs)) == 2): continue
        (a, b) = fs
        # check the factors are themselves binary palindromes
        if not (is_npalindrome(a, base=2) and is_npalindrome(b, base=2)): continue
        # check the multiplication works if the binary factorisation is interpreted as decimal
        (nx, ax, bx) = (nconcat(nsplit(x, base=2), base=10) for x in (n, a, b))
        if not (ax * bx == nx): continue
        # check the factors are prime if interpreted as decimal
        if not (is_prime(ax) and is_prime(bx)): continue
        # output solution
        printf("{a:b} * {b:b} = {n:b} [base 2] -> {a} * {b} = {n} [base 10]")
      

      Solution: The sum is: 11 × 101 = 1111.

      In decimal both 11 and 101 are prime.

      In binary this corresponds to: 3 × 5 = 15, and both 3 and 5 are prime.

      Like

  • Unknown's avatar

    Jim Randell 10:20 am on 5 March 2023 Permalink | Reply
    Tags:   

    Brainteaser 1071: Particular palindromes 

    From The Sunday Times, 13th February 1983 [link]

    When either of a [particular] pair of numbers which differ by twenty-two is added to its own square, the result is a numerical palindrome between ten million and a hundred million.

    One way of finding the pair could be, of course, by extensive trial-and-error, working through the six thousand or so possibilities that lie in the given range, and electronic assistance would surely be appreciated in these circumstances.

    It should come as some relief, therefore, to puzzlers not so equipped to know that an answer can be found by performing less than twenty simple calculations (in which a calculator may nevertheless be usefully employed), none involving the square of a four-digit number, and that a further similar number of such calculations can show that no other answer is possible.

    What is the pair?

    This puzzle is included in the book The Sunday Times Book of Brainteasers (1994).

    [teaser1071]

     
    • Jim Randell's avatar

      Jim Randell 10:20 am on 5 March 2023 Permalink | Reply

      A brute force approach considers 6838 values, which is what the following Python program does.

      It runs in 61ms. (Internal runtime is 4.7ms).

      Run: [ @replit ]

      from enigma import (irange, inf, is_npalindrome, printf)
      
      # function to apply
      f = lambda x: x * (x + 1)
      
      # consider possible numbers
      vs = dict()
      for n in irange(0, inf):
        v = f(n)
        if v < 10000000: continue
        if v > 100000000: break
        # is the result a palindrome?
        if is_npalindrome(v):
          # have we recorded (n - 22)?
          v2 = vs.get(n - 22)
          if v2 is not None:
            # output solution
            printf("f({n}) = {v}; f({n2}) = {v2}", n2=n - 22)
          # record this value
          vs[n] = v
      

      Solution: The numbers are 5291, 5313.

      We have:

      5313 − 5291 = 22

      f(5291) = 27999972
      f(5313) = 28233282

      In fact these are the only two 8-digit palindromes that are the product of 2 consecutive integers.

      Like

      • Jim Randell's avatar

        Jim Randell 10:45 am on 5 March 2023 Permalink | Reply

        This puzzle was included in the book Microteasers (1986) by Victor Bryant.

        Here is the BBC BASIC program given in the text. It looks for palindromic 8-digit numbers that are the product of two consecutive integers, and prints them out. So it doesn’t look for a pair of numbers that differ by 22.

        >LIST
            5 REM Victor Bryant program for Teaser 1071
            6 REM from "Microteasers" (1986)
           10 REM We want N + N^2 to be an 8-digit palindrome
           15 start% = TIME
           20 N = 3000
           30 REPEAT
           40   N = N + 1
           50   M = N + N*N
           60   L = LEN(STR$(M))
           70   IF L <> 8 THEN 150
           80   REM We now work out the Dth digit from the right and the Dth digit from the left and see if they are the same
           90   D = 0
           91   REPEAT
           92     D = D + 1
          100     left$ = MID$(STR$(M), D, 1)
          110     right$ = MID$(STR$(M), 9 - D, 1)
          120   UNTIL D = 4 OR left$ <> right$
          130   REM if left$ = right$ when we get to this line then M = palindrome
          140   IF left$ = right$ THEN PRINT N, M
          150 UNTIL L > 8
          155 PRINT "Time = ";(TIME - start%) / 100;"s"
        >RUN
              5291  27999972
              5313  28233282
        Time = 322.32s
        >
        

        Like

      • Jim Randell's avatar

        Jim Randell 3:40 pm on 5 March 2023 Permalink | Reply

        A little bit of analysis can significantly reduce the number of cases tested:

        In order for n(n + 1) to be a palindrome it cannot be divisible by 10, so neither n nor (n + 1) can be divisible by 5 (as one of them will be even).

        And if (n + 22)(n + 23) is a palindrome, neither (n + 22) nor (n + 23) can be divisible by 5.

        So the residue of n mod 5 cannot be 0, 2, 3, 4. Hence it must be 1.

        So we only need to consider n values of the form (5k + 1).

        Also if n(n + 1) is an 8-digit palindrome, say ABCDDCBA then we have:

        n(n + 1) = 10000001.A + 1000010.B + 100100.C + 11000.D
        n(n + 1) = 11.(909091.A + 90910.B + 9100.C + 1000.D)

        So one of n, (n + 1) must be divisible by 11. (And also one of (n + 22), (n + 23) but that follows directly).

        So here is a program that only considers 248 candidate numbers, and has an internal runtime of 491µs.

        Run: [ @replit ]

        from enigma import (irange, inf, is_npalindrome, nsplit, printf)
        
        # function to apply
        f = lambda x: x * (x + 1)
        
        # consider possible numbers
        for n in irange(1, inf, step=5):
          if n % 11 not in {0, 10}: continue
          # apply the function
          v = f(n)
          if v < 10_000_000: continue
          v2 = f(n + 22)
          if v2 > 100_000_000: break
          # is the result a palindrome?
          if is_npalindrome(v) and is_npalindrome(v2):
            printf("f({n}) = {v}; f({n2}) = {v2}", n2=n + 2)
        

        In particular using this approach I was able to write a modified version of Victor’s BBC BASIC program that reduced the runtime from 5m22s (Victor’s original program) to 13.9s (my modified program).

        >LIST
           10 REM Modification of Victor Bryant program for Teaser 1071
           20 REM from "Microteasers" (1986)
           30 REM We want N + N^2 to be an 8-digit palindrome
           40 start% = TIME
           50 FOR N = 3161 TO 9999 STEP 5
           60   IF N MOD 11 <> 0 AND N MOD 11 <> 10 THEN 140
           70   P = N + N*N
           80   IF NOT FNpal(STR$(P)) THEN 140
           90   M = N + 22
          100   Q = M + M*M
          110   IF NOT FNpal(STR$(Q)) THEN 140
          120   PRINT N, P
          130   PRINT M, Q
          140 NEXT N
          150 PRINT "Time = ";(TIME - start%) / 100;"s"
          160 END
          170 REM check for 8 character palindrome
          180 DEF FNpal(M$)
          190   IF LEN(M$) <> 8 THEN =FALSE
          200   FOR D = 1 TO 4
          210     left$ = MID$(M$, D, 1)
          220     right$ = MID$(M$, 9 - D, 1)
          230     IF left$ <> right$ THEN =FALSE
          240   NEXT D
          250   =TRUE
        >RUN
              5291  27999972
              5313  28233282
        Time = 13.9s
        

        But the setter must have some other analysis in mind to reduce the number of calculations to less than 20.

        Like

    • GeoffR's avatar

      GeoffR 1:29 pm on 5 March 2023 Permalink | Reply

      
      # testing for (num + square(num)) between 10 million and 100 million approx.
      # LB = 3161 + 3161 ** 2 = 9,995,082
      # UB = 9999 + 9999 ** 2 = 99,990,000
      for n in range(3161, 10000):
        sum_prod = n + n ** 2
        # check if this number is a numerical palindrome
        if str(sum_prod) == str(sum_prod)[::-1]:
          # Second number is 22 more than first number
          n2 = n + 22
          sum_prod2 = n2 + n2 ** 2
          # check if this number is a numerical palindrome
          if str(sum_prod2) == str(sum_prod2)[::-1]:
            print(f"Pair of numbers are {n} and {n2}.")
            print(f"Associated Palindromes are {sum_prod} and {sum_prod2}.")
              
      # Pair of numbers are 5291 and 5313.
      # Associated Palindromes are 27999972 and 28233282.
      
      

      Like

    • GeoffR's avatar

      GeoffR 8:57 am on 6 March 2023 Permalink | Reply

      % A Solution in MiniZinc
      include "globals.mzn";
      
      % Pair of required numbers 
      var 3161..9999:N1;
      var 3161..9999:N2;
      
      % Palindrome digits for both palindromes
      var 1..9:A; var 0..9:B; var 0..9:C; var 0..9:D;
      var 1..9:G; var 0..9:H; var 0..9:I; var 0..9:J; 
       
      % Two eight digit palindromes
      var 10000000..99999999:ABCDDCBA = A * pow(10,7) + B * pow(10,6) + C * pow(10,5)
      + D * pow(10,4) + D * pow(10,3) + C * pow(10,2) + B * pow(10,1) + A;
      
      var 10000000..99999999: GHIJJIHG = G * pow(10,7) + H * pow(10,6) + I * pow(10,5)
      + J * pow(10,4) + J * pow(10,3) +  I * pow(10,2) + H * pow(10,1) + G;
      
      % Palindrome formation
      constraint N1 + N1 * N1 == ABCDDCBA;   % 1st 8-digit palindrome
      
      % Pair of numbers differ by twenty-two
      constraint N2 == N1 + 22;
      constraint N2 + N2 * N2 == GHIJJIHG;   % 2nd 8-digit palindrome
      
      solve satisfy;
      
      output ["Two required numbers are " ++ show(N1) ++ " and " ++ show(N2) 
      ++ "\n" ++ "Palindromes are " ++ show(ABCDDCBA) ++ " and " ++ show(GHIJJIHG)];
      
      % Two required numbers are 5291 and 5313
      % Palindromes are 27999972 and 28233282
      % ----------
      % ==========
      
      
      

      Like

    • John Crabtree's avatar

      John Crabtree 4:59 pm on 8 March 2023 Permalink | Reply

      f(N) = N(N+1) = “ABCDDCBA” = 0 (mod 11) as the sum of alternating digits is the same
      f(N+22) – f(N) = 44N + 506
      The first and last digits do not change. The second digit from the left, B, must either be the same or increase by 1.
      If it stays the same, 44N + 506 = 0 (mod 100) with no solution.
      If it increases by 1, 44N + 506 = 10 (mod 100) which leads to N = 16 mod 25

      41*42 = 66*67 = 22 (mod 100)
      sqrt(22) = 4.690 and sqrt(23) = 4.795
      4741 = 0 (mod 11), but f(4741+22) must start with 22 and is invalid
      4766 = 3 (mod 11)

      16*17 = 91*92 = 72 (mod 100)
      sqrt(27) = 5.196 and sqrt(28) = 5.291
      5191 = 10 (mod 11), but is too small
      5216 = 2 (mod 11)
      5291 = 0 mod 11, and f(5191+22) must start with 28

      And so the numbers must be 5291 and 5313.
      At this point the calculator is very useful to find that
      f(5291) = 27,999,922 and f(5313) = 28,233,282

      There are not many calculations in this solution. I do not understand the setter’s statement about needing as many calculations again to show that the solution is unique. That is included above.

      Like

      • John Crabtree's avatar

        John Crabtree 5:50 am on 10 March 2023 Permalink | Reply

        Simplifying, N = -34 + 275k = 10 (mod 11); or N = 66 + 275k = 0 (mod 11)
        With AB = 22 or 27, there are only two possible values of N:
        4741 = 4675 (17 * 275) + 66, but f(4741 + 22) is invalid
        5291 = 5225 (19 * 275) + 66, and f(5291 + 22) = f(5313) is valid

        Like

  • Unknown's avatar

    Jim Randell 8:34 am on 12 February 2023 Permalink | Reply
    Tags: ,   

    Brain-Teaser 931: Seven primes for seven brothers 

    From The Sunday Times, 25th May 1980 [link]

    Large families often have problems, particularly when it comes to deciding who has first choice, etc.

    My six brothers and I solved this particular one by devising our own dice game. Each of us in turn would roll a die four times and put the results together in that order to form a four-figure number. (So that, for example: 6 followed by 2, then 3 and 1, gives the number 6231). We would each do this and the one of us getting the highest four-figure number would be declared the winner.

    One such game had some very strange results. Each of us got a different prime number, using the same four different digits. The average of the seven primes was a perfect square, to which Jon’s number was the nearest.

    The difference between Ron’s and Don’s numbers, multiplied by one of the numbers from the die, gave the difference between Len’s and Ken’s numbers.

    Omitting Ben’s score, the total could have been formed by throwing the die five times. And so could the total of the numbers thrown by Len, Ken, Ron and me.

    What was my score, and who ate the biggest piece of apple pie?

    The originally published version of this puzzle was flawed, so the version above was taken from the book Microteasers (1986), in which it was noted:

    There is an interesting postscript to [this] puzzle. When it first appeared, the condition “each of us got a different prime number using the same four different digits” was given as “each of us got a different prime number; two digits never came up”. That allowed numbers like 5651, which was not the intention at all. The odd thing is that all the readers who sent in answers found the intended solution anyway. So perhaps, even if one relaxes the condition about all the primes using four different digits, the teaser still has a unique solution. The keener reader might like to adapt the program to take four digits in turn and see how many primes can be made from those four (but not necessarily using all four each time). Then you have to consider all possible sets of seven from those. We leave this much harder problem as an exercise.

    However the original formulation of the puzzle does not give a unique solution.

    [teaser931]

     
    • Jim Randell's avatar

      Jim Randell 8:36 am on 12 February 2023 Permalink | Reply

      The original formulation of the puzzle is flawed, so I used the version from the Microteasers (1986) book.

      The following Python program runs in 58ms. (Internal runtime is 1.2ms).

      Run: [ @replit ]

      from enigma import (irange, primes, nconcat, nsplit, subsets, div, is_square, diff, printf)
      
      # digits on a die
      digits = set(irange(1, 6))
      
      # check the numbers <ns> form a valid solution
      def check(ns):
        # total must be > 4-digit
        t = sum(ns)
        if t < 10000: return
        mx = max(ns)
        # calculate the mean
        m = div(t, len(ns))
        if m is None or not is_square(m): return
        # J is the closest to the mean
        fn = lambda n: abs(n - m)
        ns = sorted(ns, key=fn)
        J = ns.pop(0)
        if not fn(J) < fn(ns[0]): return
        # choose R, D values
        for (R, D) in subsets(ns, size=2):
          d = abs(R - D)
          # find another pair that is a multiple of d for L, K
          for (L, K) in subsets(diff(ns, {R, D}), size=2):
            x = div(abs(L - K), d)
            if x not in digits: continue
            # remaining pair are B and M
            for (B, M) in subsets(diff(ns, {R, D, L, K}), size=2, select="P"):
              # total less B can be expressed with 5 dice
              ds = nsplit(t - B)
              if not (len(ds) == 5 and digits.issuperset(ds)): continue
              # as can L + K + R + M
              for (R_, D_) in [(R, D), (D, R)]:
                ds = nsplit(L + K + R_ + M)
                if not (len(ds) == 5 and digits.issuperset(ds)): continue
                # output solution
                printf("J={J} R={R_} D={D_} L+K={L}+{K} B={B} M={M} [m={m} d={d} x={x}]")
                n2t = { J: 'Jon', R_: 'Ron', D_: 'Don', L: '{LK}en', K: '{KL}en', B: 'Ben', M: 'Me'}
                printf("-> Me = {M}; max = {mx}", mx=n2t[mx])
      
      # only 4 digits are used
      for ds in subsets(digits, size=4, fn=set):
        # collect possible primes
        ps = list(n for n in subsets(ds, size=len, select="P", fn=nconcat) if primes.is_prime(n))
        # choose 7 of the primes
        for ns in subsets(ps, size=7):
          # and check for a solution
          check(ns)
      

      Solution: The setter scored 4153. And Don got the highest score.

      There is only one set of 4 dice digits that can form 7 primes, and this set gives exactly seven primes, so we just need to distribute them amongst the brothers according to the given conditions.

      The scores are:

      Len = 1543
      Ken = 1453
      Jon = 3541
      Me = 4153
      Ben = 4513
      Ron = 5413
      Don = 5431

      (Although Ken and Len can swap scores and still give a valid solution).

      The mean value is: 3721 = 61², and Jon has the closest value to this.

      The difference between Ron and Don is 18. And the difference between Len and Ken is 90 = 5 × 18.

      The total without Ben is 21534, which uses 5 dice digits.

      The total of Len, Ken, Ron and Me is 12562, which also uses 5 dice digits.


      However, with the formulation of the puzzle (as originally published in The Sunday Times) there are many further solutions, which the program above can be adapted to find.

      For example, the following primes use only the digits: 1, 3, 5, 6:

      Ben = 1151
      Jon = 5153
      Len = 5651
      Ron = 6133
      Ken = 6311
      Don = 6353
      Me = 6551

      The mean value is: 5329 = 73², and Jon has the closest value to this.

      The difference between Ron and Don is 220. And the difference between Len and Ken is 660 = 3 × 220.

      The total without Ben is: 36152, which uses 5 dice digits.

      The total of Len, Ken, Ron and Me is: 24646, which also uses 5 dice digits.

      And in this case the answer would be that the setters score is 6551, and this is also the highest of the scores.

      Like

    • Hugh Casement's avatar

      Hugh Casement 7:15 pm on 13 February 2023 Permalink | Reply

      There are only 32 four-digit primes that use just the digits 1 to 6 with no repeat.
      And the subset forming the solution to this puzzle is the only one with seven members.
      There is one with six members: 1523, 2153, 2351, 2531, 3251, 5231.
      I haven’t tried constructing a puzzle with those numbers.

      Like

    • GeoffR's avatar

      GeoffR 8:50 am on 15 February 2023 Permalink | Reply

      I found the 32 no. 4-digit primes and divided them into sets of primes with the same 4 digits. For a dice range of (1..6), all primes must end in 1 or 3.

      There was 1 set of 7 primes, 1 set of 6 primes, 2 sets of 4 primes, 2 sets of 3 primes, 2 sets of 2 primes, and 1 set of 1 prime.

      {4231, 2341, 2143, 1423}
      {4513, 5413, 1543, 1453, 3541, 5431, 4153} – 7 no. primes in this set
      {2531, 2153, 2351, 5231, 1523, 3251}
      {4523, 4253, 2543}
      {3461, 6143}
      {6421, 4621, 4261}
      {4561, 4651, 6451, 5641}
      {6521, 5261}
      {5623}

      % A Solution in MiniZinc
      include "globals.mzn";
      
      set of int : primes = {4513, 5413, 1543, 1453, 3541, 5431, 4153};
      
      var primes: Len; var primes: Ken; var primes: Jon; var primes: Me;
      var primes: Ben; var primes: Ron; var primes: Don;
      
      constraint all_different([Len, Ken, Jon, Me, Ben, Ron, Don]);
      
      predicate is_sq(var int: y) =
      exists(z in 1..ceil(sqrt(int2float(ub(y))))) (z*z = y );
      
      % The average of the seven primes was a perfect square.
      constraint is_sq((4513 + 5413 + 1543 + 1453 + 3541 + 5431 + 4153) div 7);
      var 3000..4000: average = (4513 + 5413 + 1543 + 1453 + 3541 + 5431 + 4153) div 7;
      
      % The difference between Ron’s and Don’s numbers, multiplied by one of the numbers
      % from the die, gave the difference between Len’s and Ken’s numbers.
      var 1..300:d1; var 1..6:m;  % difference d1 and multiplier m from dice values.
      
      constraint abs (Ron - Don) == d1;
      constraint d1 * m == (Len - Ken);
      
      % The total without Ben uses 5 dice digits.
      var int: total = 4513 + 5413 + 1543 + 1453 + 3541 + 5431 + 4153; 
      
      var 20000..26000: tot_minus_Ben = total - Ben;
      
      % Digits of (total - Ben)
      var 1..6:a; var 1..6:b; var 1..6:c; var 1..6:d; var 1..6:e;
      
      constraint tot_minus_Ben div 10000 == a /\ a in {1,2,3,4,5,6};
      constraint tot_minus_Ben div 1000 mod 10 == b /\ b in {1,2,3,4,5,6};
      constraint tot_minus_Ben div 100 mod 10 == c /\ c in {1,2,3,4,5,6};
      constraint tot_minus_Ben div 10 mod 10 == d /\ d in {1,2,3,4,5,6};
      constraint tot_minus_Ben mod 10 == e /\ e in {1,2,3,4,5,6};
      
      % The total of Len, Ken, Ron and Me also uses 5 dice digits.
      var 1..6:f; var 1..6:g; var 1..6:h; var 1..6:i; var 1..6:j;
      
      var 12000..20000: LKRMe = Len + Ken + Ron + Me;
      
      constraint LKRMe div 10000 == f /\ f in {1,2,3,4,5,6};
      constraint LKRMe div 1000 mod 10 == g /\ g in {1,2,3,4,5,6};
      constraint LKRMe div 100 mod 10 == h /\ h in {1,2,3,4,5,6};
      constraint LKRMe div 10 mod 10 == i /\ i in {1,2,3,4,5,6};
      constraint LKRMe mod 10 == j /\ j in {1,2,3,4,5,6};
      
      solve minimize( abs(Jon - average));
      
      output ["[Len, Ken, Jon, Me, Ben, Ron, Don] = " 
      ++ show([Len, Ken, Jon, Me, Ben, Ron, Don]) 
      ++ "\n" ++ "[a,b,c,d,e ] = " ++ show( [a,b,c,d,e] )
      ++ "\n" ++ "[f,g,h,i,j ] = " ++ show( [f,g,h,i,j] ) 
      ++ "\n" ++ "Average = " ++ show(average)];
      
      % [Len,   Ken, Jon,   Me,   Ben, Ron,  Don] = 
      % [1543, 1453, 3541, 4153, 4513, 5413, 5431]
      % [a,b,c,d,e ] = [2, 1, 5, 3, 4]
      % [f,g,h,i,j ] = [1, 2, 5, 6, 2]
      % Average = 3721
      % ----------
      % ==========
      
      
      
      

      Like

  • Unknown's avatar

    Jim Randell 2:36 pm on 30 May 2021 Permalink | Reply
    Tags:   

    Brain teaser 1000: One thousand down 

    From The Sunday Times, 20th September 1981 [link]

    This auspiciously-numbered Brain-teaser has given my wife a chance to take stock of the teasers which she has tried over the years. When the Brain-teasers started to be numbered she did one of the early ones and took most of that Sunday over it. So she decided not to spend every Sunday on them, but only to do those teasers whose numbers were multiples of that first one she had tried.

    This worked very well for a long time until one Sunday there was an exceptional teaser which she couldn’t resist doing, even though she had done the previous week’s. She so enjoyed doing that extra puzzle that she decided she would in future try precisely those teasers whose numbers were the sum of two numbers (possibly the same) of teasers which she had tried previously. She didn’t try last week’s, but she’ll be busy today trying this one. But the rest of us have suddenly realised with horror that we’re never going to get a decent Sunday lunch again, because my wife is going to have to do every Brain-teaser from now on.

    (1) What was the first teaser which she tried?
    (2) What was the number of that “exceptional teaser which she couldn’t resist”?
    (3) How many of the first 1,000 Brain-teasers will she have tried?

    [teaser1000]

     
    • Jim Randell's avatar

      Jim Randell 2:37 pm on 30 May 2021 Permalink | Reply

      (See also: Enigma 1154, Enigma 1194, Enigma 228, Enigma 122).

      If the first Teaser is number x, then she will try 2x, 3x, 4x, …. Until one day, having done kx she can’t resist also doing (kx + 1).

      So we can consider this to be a “money changing” problem, using denominations of x and y = (kx + 1).

      And the largest amount that cannot be expressed using these denominations is 999.

      This is the Frobenius Number of the denominations:

      F(x, y) = x⋅y − x − y

      And the number of amounts that are not expressible using the denominations is:

      N(x, y) = (x − 1)(y − 1) / 2

      The following Python program runs in 53ms.

      Run: [ @replit ]

      from enigma import irange, div, printf
      
      F = lambda x, y: x * y - x - y
      N = lambda x, y: div((x - 1) * (y - 1), 2)
      
      # consider the first teaser x (< 100)
      for x in irange(2, 99):
        # and consider multiples of x < 1000
        for kx in irange(2 * x, 997, step=x):
          y = kx + 1
          if F(x, y) == 999:
            # output solutions
            n = 1000 - N(x, y)
            printf("(1) {x}; (2) {y}; (3) {n}") 
      

      Solution: (1) The first Teaser she tried was number 5; (2) The Teaser she couldn’t resist was number 251; (3) She will have tried 500 of the first 1000 Teasers.

      Like

      • Jim Randell's avatar

        Jim Randell 4:59 pm on 30 May 2021 Permalink | Reply

        And the following program shows the numbers of the Teasers that were attempted:

        from enigma import irange, printf
        
        (x, y) = (5, 251)
        
        # collect attempted teasers
        ns = set()
        
        # attempt teaser n
        def attempt(n):
          ns.add(n)
          printf("{n}" + ("" if len(ns) % 15 == 0 else " \\"))
        
        # consider increasing teaser numbers
        for n in irange(1, 1000):
          # start by doing multiples of x
          if n < y:
            if n % x == 0:
              attempt(n)
          elif n == y:
            # and then do y
            attempt(n)
          else:
            # and then any number that is the sum of two previous numbers
            if any(n - a in ns for a in ns):
              attempt(n)
        
        printf("\nattempted = {n}", n=len(ns))
        

        Output:

        5 10 15 20 25 30 35 40 45 50 55 60 65 70 75
        80 85 90 95 100 105 110 115 120 125 130 135 140 145 150
        155 160 165 170 175 180 185 190 195 200 205 210 215 220 225
        230 235 240 245 250 251 255 256 260 261 265 266 270 271 275
        276 280 281 285 286 290 291 295 296 300 301 305 306 310 311
        315 316 320 321 325 326 330 331 335 336 340 341 345 346 350
        351 355 356 360 361 365 366 370 371 375 376 380 381 385 386
        390 391 395 396 400 401 405 406 410 411 415 416 420 421 425
        426 430 431 435 436 440 441 445 446 450 451 455 456 460 461
        465 466 470 471 475 476 480 481 485 486 490 491 495 496 500
        501 502 505 506 507 510 511 512 515 516 517 520 521 522 525
        526 527 530 531 532 535 536 537 540 541 542 545 546 547 550
        551 552 555 556 557 560 561 562 565 566 567 570 571 572 575
        576 577 580 581 582 585 586 587 590 591 592 595 596 597 600
        601 602 605 606 607 610 611 612 615 616 617 620 621 622 625
        626 627 630 631 632 635 636 637 640 641 642 645 646 647 650
        651 652 655 656 657 660 661 662 665 666 667 670 671 672 675
        676 677 680 681 682 685 686 687 690 691 692 695 696 697 700
        701 702 705 706 707 710 711 712 715 716 717 720 721 722 725
        726 727 730 731 732 735 736 737 740 741 742 745 746 747 750
        751 752 753 755 756 757 758 760 761 762 763 765 766 767 768
        770 771 772 773 775 776 777 778 780 781 782 783 785 786 787
        788 790 791 792 793 795 796 797 798 800 801 802 803 805 806
        807 808 810 811 812 813 815 816 817 818 820 821 822 823 825
        826 827 828 830 831 832 833 835 836 837 838 840 841 842 843
        845 846 847 848 850 851 852 853 855 856 857 858 860 861 862
        863 865 866 867 868 870 871 872 873 875 876 877 878 880 881
        882 883 885 886 887 888 890 891 892 893 895 896 897 898 900
        901 902 903 905 906 907 908 910 911 912 913 915 916 917 918
        920 921 922 923 925 926 927 928 930 931 932 933 935 936 937
        938 940 941 942 943 945 946 947 948 950 951 952 953 955 956
        957 958 960 961 962 963 965 966 967 968 970 971 972 973 975
        976 977 978 980 981 982 983 985 986 987 988 990 991 992 993
        995 996 997 998 1000 
        attempted = 500
        

        Like

    • John Crabtree's avatar

      John Crabtree 9:54 pm on 31 May 2021 Permalink | Reply

      If y = n * x + 1, this leads to (x – 1) * n * x = 1000 = 2^3 * 5^3
      And so x = 5, n = 50, y = 251, etc

      Like

      • Jim Randell's avatar

        Jim Randell 8:39 am on 1 June 2021 Permalink | Reply

        @John: A neat bit of analysis. It also provides the answer to (3) directly:

        y = kx + 1
        F(x, y) = xy − x − y = 999
        ⇒ kx(x − 1) = 1000

        N(x, y) = (x − 1)(y − 1) / 2 = (x − 1)kx / 2 = 1000/2

        Like

  • Unknown's avatar

    Jim Randell 9:05 am on 29 March 2021 Permalink | Reply
    Tags: by: L. J. Upton   

    Brainteaser 1040: An uncommon number 

    From The Sunday Times, 4th July 1982 [link]

    Your problem this week is to find an unusual nine-digit number. It comprises the digits from 1 to 9, in some order, each used once and only once.

    The number formed by the first digit (reading from the left) is exactly divisible by 1 (which doesn’t tell you a lot!), the number formed by the first two digits is exactly divisible by 2, that formed by the first three digits is exactly divisible by 3, and so on, which the number formed by the first eight digits being divisible by 8, and with the complete number of nine digits being divisible by 9.

    It is perhaps surprising that such a number exists, and even more surprising that is should be unique.

    What is the number?

    This puzzle is included in the books Microteasers (1986) and The Sunday Times Book of Brainteasers (1994).

    [teaser1040]

     
    • Jim Randell's avatar

      Jim Randell 9:06 am on 29 March 2021 Permalink | Reply

      This puzzle has also appeared recently as Puzzle #102, Teaser 3053.

      See my comment on Enigmatic Code for the solution.


      Here are the results for an n-digit (decimal) number, consisting of some arrangement of the digits 1..n, such that the leftmost k digits are divisible by k, for k = 1..n:

      [1] = 1
      [1..2] = 12
      [1..3] = 123; 321
      [1..4] = none
      [1..5] = none
      [1..6] = 123654; 321654
      [1..7] = none
      [1..8] = 38165472
      [1..9] = 381654729
      [1..0] = 3816547290

      And taking the final entry, a 10-digit number in base 10, using all 10 digits, such that the leftmost k digits are divisible by k, for k = 1..10; we can extend this to other bases:

      base 2: 10
      base 4: 1230; 3210
      base 6: 143250; 543210
      base 8: 32541670; 52347610; 56743210
      base 10: 3816547290
      base 12: none
      base 14: 9C3A5476B812D0
      base 16-30: none

      (see: OEIS A11456 [ @oeis ]).

      Like

      • Jim Randell's avatar

        Jim Randell 6:01 pm on 29 March 2021 Permalink | Reply

        And if we drop the requirement that digits cannot be reused, we can see that any left prefix of a polydivisible number [ @wikipedia ] must also be polydivisible.

        This program generates all possible polydivisible numbers in a given base (and with a given set of digits):

        from enigma import (irange, int2base, args, printf)
        
        ds = args([10], 0, int)
        base = ds.pop(0)
        if not ds: ds = list(irange(base))
        printf("[base = {base}; digits = {ds}]")
        
        (k, ns) = (1, list(ds))
        while ns:
          (k_, ns_) = (k + 1, list())
          
          for n in ns:
            # output current numbers
            printf("{k} -> {n}", n=int2base(n, base=base))
            # can we extend this number?
            if n > 0:
              for d in ds:
                n_ = base * n + d
                if n_ % k_ == 0:
                  ns_.append(n_)
        
          (k, ns) = (k_, ns_)
        

        And we find that the longest base 10 polydivisible number, using the digits 0-9 (although 1 and 9 do not appear), has 25 digits:

        3608528850368400786036725

        In base 16 there are 3 maximal length (39-digit) polydivisible numbers:

        34E4A468166CD8604EC0F8106AB4326098286CF;
        AA44CE207C78FC30003C3CC0D8382E2078D07EF;
        FAE06678C2E884607EB8B4E0B0A0F0603420342

        Like

  • Unknown's avatar

    Jim Randell 8:08 am on 8 September 2020 Permalink | Reply
    Tags:   

    Brainteaser 1108: Field fare 

    From The Sunday Times, 30th October 1983 [link]

    The field near to our home is rectangular. Its longer sides run east to west. In the south-east corner there is a gate. In the the southern fence there is a stile a certain number of yards from the south-west corner. In the northern fence there is a stile, the same certain number of yards from the north-east corner. A straight path leads across the field from one stile to the other. Another straight path from the gate is at right angles to the first path and meets it at the old oak tree in the field.

    When our elder boy was ten, and his brother five years younger, they used to race from opposite ends of a long side of the field towards the stile in that as the target. But later, when they were a little less unevenly matched, they raced from opposite stiles towards the oak as the target. Of course the younger boy raced over the shorter distances. This change of track gave the younger boy 9 yards more and the elder boy 39 yards less than before to reach the target.

    The sides of the field and the distances of the oak tree from each of the stiles are all exact numbers of yards.

    How far apart are the two stiles, and how far is the oak tree from the gate?

    [teaser1108]

     
    • Jim Randell's avatar

      Jim Randell 8:09 am on 8 September 2020 Permalink | Reply

      If we suppose the north and south boundaries of the field are separated by a distance of a, and the stiles divide the these boundaries into sections with length x and y, and the distances from the tree to the stiles are b and c, and the distance from the tree to the corner is z. Then we have a layout like this:

      When the children were younger they would run distances x and y.

      And when they were older the distances are b and c.

      Hence:

      b = x + 9
      c = y − 39
      ⇒ y − x = c − b + 48

      The distance between the two stiles, (b + c) forms the hypotenuse of a Pythagorean triangle with other sides of (y − x) = (c − b + 48) and a (triangle: S1 Y S2).

      So we can consider Pythagorean triples for this triangle. One of the non-hypotenuse sides corresponds to a, and the other when added to the hypotenuse gives:

      (b + c) + (c − b + 48) = 2c + 48

      So choosing one of the sides for a, allows us to calculate the value for c, and then b, x, y, z.

      The distance G S2 is the hypotenuse of the two triangles (G T S2) and (G X S2), and we can check that these hypotenuses match.

      The following Python program runs in 58ms.

      Run: [ @replit ]

      from enigma import (pythagorean_triples, div, sqrt, printf)
      
      # consider pythagorean triples corresponding to (a, c - b + 48, b + c)
      
      for (X, Y, Z) in pythagorean_triples(1000):
        # choose a side for a
        for (a, other) in [(X, Y), (Y, X)]:
          # and: other + Z = 2c + 48
          c = div(other + Z - 48, 2)
          if c is None or c < 1: continue
          b = Z - c
          x = b - 9
          y = c + 39
          if not (0 < b < c and 0 < x < y): continue
          # calculate z^2
          z2 = y * y - c * c
          if not (b * b + z2 == a * a + x * x): continue
          # output solution
          printf("({X}, {Y}, {Z}) -> a={a} b={b} c={c}, x={x} y={y} z={z:g}", z=sqrt(z2))
      

      Solution: The stiles are 200 yards apart. The oak tree is 117 yards from the gate.

      The short side of the field is 120 yards.

      The long side is 230 yards, and this is split into sections of 35 and 195 yards by the stiles.

      The oak tree is 44 yards from one stile and 156 yards from the other.


      This puzzle appeared in the 1986 book Microteasers (p 4) by Victor Bryant, in which he deals with solving puzzles using the BBC Micro. (See: [ @EnigmaticCode ]).

      Here is Victor Bryant’s BBC BASIC program (slightly modified by me to stop after the first solution is encountered, and print the run time for the program):

      >LIST
         10 REM Victor Bryant program for Teaser 1108
         15 start% = TIME
         20 FOR c = 26 TO 500  
         30   FOR b = 25 TO c - 1
         40     a = SQR((c + 39)^2 - c^2 + b^2 - (b - 9)^2)
         50     IF a <> INT(a) THEN 70
         60     IF a^2 <> (b + c)^2 - (c - b + 48)^2 THEN 70
         65     PRINT "Distances: stiles - tree = "; b; " and "; c; " & short side = "; a
         66     GOTO 85
         70   NEXT b
         80 NEXT c
         85 PRINT "(Time = "; (TIME - start%) / 100; "s)"
      
      >RUN
      Distances: stiles - tree = 44 and 156 & short side = 120
      (Time = 250.2s)
      
      >
      

      Here is a Python program using the same approach. It takes 65ms to find the first solution, or 137ms to run to completion. (On an emulated BBC Micro Victor’s program takes about an hour to run to completion).

      from enigma import (irange, subsets, is_square, printf)
      
      for (b, c) in subsets(irange(25, 500), size=2):
        a = is_square((c + 39)**2 - c**2 + b**2 - (b - 9)**2)
        if a is None: continue
        if a**2 + (c - b + 48)**2 != (b + c)**2 : continue
        printf("a={a} b={b} c={c}")
        break
      

      Comparing internal runtimes we find that my program runs in 2.4ms (to completion), and the port of Victor’s program in 17.3ms (to first solution; 219ms to completion). They search a similar solution space, (i.e. distance S1 S2 less than 1000 yards).

      Like

      • Jim Randell's avatar

        Jim Randell 3:08 pm on 14 September 2020 Permalink | Reply

        Here’s my analytical solution:

        We have:

        x = b − 9
        y = c + 39

        and

        y² = c² + z²
        (c + 39)² = c² + z²
        2.39.c + 39.39 = z²
        c = (z² − 39.39) / 2.39
        c = (z²/39 − 39)/2

        Now, c is an integer, so z²/39 is an odd integer:

        z²/39 = 2k + 1
        z² = 39(2k + 1)

        and:

        c = (2k + 1 − 39)/2
        c = k − 19

        and: c > b > 9, so k > 29.

        Also, we have:

        a² = (b + c)² − (c − b + 48)²
        a² = (b² + 2bc + c²) − (b² + c² − 2bc − 96b + 96c + 2304)
        a² = 4bc − 96b + 96c + 2304
        a² = 4(b − 24)(c + 24)
        a² = 4(b − 24)(k + 5)

        So: b > 24k > 44.

        And:

        b² + z² = a² + (b − 9)²
        b² + 39(2k + 1) = 4(b − 24)(k + 5) + (b² − 18b + 81)
        78k + 39 = 4bk + 20b − 96k − 480 − 18b + 81
        2b(2k + 1) = 174k + 438
        b = (87k + 219) / (2k + 1)

        As k → ∞, b → 87/2 = 43.5, so: b ≥ 44 and k ≤ 175.

        This gives us a limited range of values for k, which we can check:

        from enigma import (irange, div, is_square, sqrt, printf)
        
        # consider possible values for k
        for k in irange(45, 175):
          # calculate a, b, c, x, y, z
          c = k - 19
          b = div(87 * k + 219, 2 * k + 1)
          if b is None or not (0 < b < c): continue
          a = is_square(4 * (b - 24) * (c + 24))
          if a is None: continue
          x = b - 9
          y = c + 39
          z = sqrt(78 * k + 39)
          if not (0 < x < y): continue
          # output solution
          printf("[k={k}] a={a} b={b} c={c}; x={x} y={y} z={z:g}")
        

        Or we can narrow down the values with further analysis:

        Now:

        (b − 24) = 39(k + 5) / (2k + 1)

        and so:

        a² = [2(k + 5)]² (39 / (2k + 1))

        The value of (2k + 1) is in the range 91 to 351, so the (39 / (2k + 1)) part, must contribute pairs of factors (which divide into the pairs of factors provided by the [2(k + 5)]² part).

        So (2k + 1) is some odd square multiple of 39 (which also means that z must be an integer).

        The only option in the required range is:

        (2k + 1) = 39×3² = 351
        k = 175
        a = 120, b = 44, c = 156
        x = 35, y = 195, z = 117

        Like

    • John Crabtree's avatar

      John Crabtree 6:11 am on 9 September 2020 Permalink | Reply

      (b + c)^2 = a^2 +(y – x)^2
      a^2 + x^2 = b^2 +z^2
      y^2 = c^2 + z^2
      Adding the three equations and simplifying gives bc + xy = z^2
      But z^2 = 39(2y – 39) = (39k)^2
      And so y = 39(k^2 + 1)/2
      Using b = x + 9 and c = y – 39, leads to x = 69/2 + 9/(2.k^2)
      For integral solutions, either k = 1 and then x = y = z = 39 which is invalid,
      or k = 3, x = 35, y = 195 and z = 117, etc with a = 120 as a check

      Like

      • John Crabtree's avatar

        John Crabtree 4:08 am on 10 September 2020 Permalink | Reply

        I should have included: a = 39k + 9/k = z + 9/k

        Like

        • Frits's avatar

          Frits 10:37 am on 10 September 2020 Permalink | Reply

          Nice solution, I checked your equations.

          I think you have to proof k (and z?) is an integer
          before only only considering k=1 and k=3.

          fi, k = 3^0.5 would also lead to an integral solution for x.

          We only know for sure that a, b, c and x,y are natural numbers.

          Like

          • John Crabtree's avatar

            John Crabtree 4:02 pm on 11 September 2020 Permalink | Reply

            Frits, thank you. I had assumed that z was a whole number, which we are not told. We also need to consider a, =(2y -30)/k before determining possible values of k. y is a whole number, and so k must be rational, = n/m. But then for y to be a whole number, m= 1, and so k is an integer.
            I think that this makes the manual solution, which should exist, complete.

            Like

        • Frits's avatar

          Frits 11:31 pm on 12 September 2020 Permalink | Reply

          Hi John,

          Unfortunately some of your text was lost during formatting. I can follow the logic if (2y -30)/k equals an integer expression. What formula or variable did you intend to use as left hand side of ” (2y -30)/k”?

          I now used opening and closing pre tags for this section.

          Like

c
Compose new post
j
Next post/Next comment
k
Previous post/Previous comment
r
Reply
e
Edit
o
Show/Hide comments
t
Go to top
l
Go to login
h
Show/Hide help
shift + esc
Cancel
Design a site like this with WordPress.com
Get started