Updates from February, 2026 Toggle Comment Threads | Keyboard Shortcuts

  • Unknown's avatar

    Jim Randell 8:13 am on 20 February 2026 Permalink | Reply
    Tags:   

    Teaser 2456: [Digit groups] 

    From The Sunday Times, 18th October 2009 [link]

    A teacher asked each of her pupils to write the digits 1 to 9 in a row and then use dashes to divide their row of digits into groups, such as in 123-4-56-789. She then asked them to add up the numbers in each group and multiply all the totals together — so the above example would give the
    answer 6×4×11×24 = 6336.

    Billy’s answer was an odd perfect square. Jilly’s answer was also a perfect square, but in her case each group of digits had more than one digit in it.

    What were Billy’s and Jilly’s rows of digits and dashes?

    This puzzle was originally published with no title, and no setter was given.

    [teaser2456]

     
    • Jim Randell's avatar

      Jim Randell 8:14 am on 20 February 2026 Permalink | Reply

      This Python program runs in 69ms. (Internal runtime is 1.6ms)

      from enigma import (irange, decompose, tuples, csum, multiply, is_square_p, printf)
      
      # the sequence of digits
      digits = list(irange(1, 9))
      n = len(digits)
      
      # divide the digits into k groups (min groups = 1, max groups = n)
      for k in irange(1, n):
        for js in decompose(len(digits), k, increasing=0, sep=0, min_v=1):
          # split the digits into the groups
          gs = list(digits[i:j] for (i, j) in tuples(csum(js, empty=1), 2))
          # calculate the result of the process
          r = multiply(sum(ns) for ns in gs)
          # both B and J found a square number
          if is_square_p(r):
            # B's was odd
            if r % 2 == 1:
              printf("Billy: {gs} -> {r}")
            # J's groups each have more than one digit
            if all(len(ns) > 1 for ns in gs):
              printf("Jilly: {gs} -> {r}")
      

      Solution: Billy = 12-3-456-78-9; Jilly = 12-3456-789.

      So:

      Billy = (1+2)×(3)×(4+5+6)×(7+8)×(9) = 18225 = 135^2
      Jilly = (1+2)×(3+4+5+6)×(7+8+9) = 1296 = 36^2

      Here is a complete list of square numbers that can be formed this way:

      12345678-9 → 324 = 18^2
      12-3456-789 → 1296 = 36^2 (only one with multiple digits per group)
      123-4-5-6789 → 3600 = 60^2
      1-2-34567-8-9 → 3600 = 60^2
      1-2-3-4-5-6789 → 3600 = 60^2
      12-345-6-789 → 5184 = 72^2
      12-3-45-6-789 → 11664 = 108^2
      1-234-567-8-9 → 11664 = 108^2
      1-23-4-5-6-789 → 14400 = 120^2
      12-3-456-78-9 → 18225 = 135^2 (only odd square)
      12-3-4-567-8-9 → 46656 = 216^2

      Like

    • ruudvanderham's avatar

      ruudvanderham 12:07 pm on 20 February 2026 Permalink | Reply

      I make expressions by putting either )*( or + between the digits 1 – 8, like
      (1)*(2+3+4+5)*(6+7)*(8)*(9)
      and then evaluate that with eval.
      For Jilly, I then also check whether the lengths of all parts split by ‘)*(‘ is greater than 2.

      import itertools
      import math
      
      for ops in itertools.product(("+", ")*("), repeat=8):
          exp = "(1" + "".join(f"{op}{i}" for i, op in enumerate(ops, 2)) + ")"
          if math.isqrt(val := eval(exp)) ** 2 == val:
              if val % 2:
                  print("Billy", exp, "=", val)
              else:
                  if all(len(part) > 2 for part in exp.split(")*(")):
                      print("Jilly", exp, "=", val)
      

      Like

      • Ruud's avatar

        Ruud 3:41 pm on 20 February 2026 Permalink | Reply

        With a more elegant check for no groups of one digit:

        import itertools
        import math
        
        for ops in itertools.product(("+", ")*("), repeat=8):
            exp = "(1" + "".join(f"{op}{i}" for i, op in enumerate(ops, 2)) + ")"
            if math.isqrt(val := eval(exp)) ** 2 == val:
                if val % 2:
                    print("Billy", exp, "=", val)
                else:
                    if all("+" in part for part in exp.split("*")):
                        print("Jilly", exp, "=", val)
        

        Like

  • Unknown's avatar

    Jim Randell 8:47 am on 17 February 2026 Permalink | Reply
    Tags: ,   

    Teaser 2457: [Wedding gifts] 

    From The Sunday Times, 25th October 2009 [link]

    On their wedding day, Lauren was 19 years old and John was older than that. John gave Lauren half of the money he had, plus a further £19, being a love token of £1 for each year of her life. Then Lauren gave John half of all the money she then had, plus £1 for each year of his life.

    The amount of money John now had was an exact multiple of the amount he would have had if the order of giving had been reversed.

    How much money did John start with?

    This puzzle was originally published with no title.

    [teaser2457]

     
    • Jim Randell's avatar

      Jim Randell 8:48 am on 17 February 2026 Permalink | Reply

      If J starts with an amount X and is a (> 19) years old. L starts with an amount Y.

      Then in the actual scenario:

      J has X; L has Y
      J→L: X/2 + 19
      J has (X/2 − 19); L has (Y + X/2 + 19)
      L→J: (Y + X/2 + 19)/2 + a
      J has (X/2 − 19 + Y/2 + X/4 + 19/2 + a) = (3X/4 + Y/2 + a − 19/2)

      In the reverse scenario:

      J has X; L has Y
      L→J: Y/2 + a
      J has (X + Y/2 + a); L has (Y/2 − a)
      J→L: (X + Y/2 + a)/2 + 19
      J has (X + Y/2 + a − (X/2 + Y/4 + a/2 + 19)) = (X/2 + Y/4 + a/2 − 19)

      And so:

      (3X/4 + Y/2 + a − 19/2) is a multiple of (X/2 + Y/4 + a/2 − 19)

      i.e., for some positive integer k:

      k = (3X/4 + Y/2 + a − 19/2) / (X/2 + Y/4 + a/2 − 19)

      k = 2 + (114 − X)/(2X + Y + 2a − 76)

      And if we want a proper multiple, then k ≥ 2.

      Considering the fractional part of the expression:

      If X > 114, then the numerator is negative, and the denominator is positive, so this is no good.

      if X = 114, then the numerator is zero, and the denominator is positive, whatever the values of Y and a are.

      If X < 114, then we need to choose values of Y and a, such that Y ≥ 2a ≥ 40, and the denominator divides into the numerator to give a positive integer.

      Here is a Python program to examine the scenarios:

      from enigma import (irange, divisors_pairs, printf)
      
      # consider possible values for X
      # X/2 >= 19 => X >= 38
      # 114 - X >= 0 => X <= 114
      
      # consider possible X values
      for X in irange(38, 114):
        n = 114 - X
        if n == 0:
          # output scenario
          printf("X = {X}; a >= 20; Y >= 2n")
        else:
          # consider possible divisors of n
          for (d, x) in divisors_pairs(n, every=1):
            k = 2 + x
            # calculate z = (Y + 2a)
            z = d + 76 - 2*X
            # which must be >= 40 + 40 = 80
            if z < 80: continue
            # consider possible a values >= 20
            for a in irange(20, 90):
              Y = z - 2 * a
              if Y < 0: break
              if Y < 2 * a: continue
              # output scenario
              printf("X = {X} [n = {n}; d = {d}] -> k = {k}; a={a} Y={Y}")
      

      Solution: John started with £ 114.

      And it doesn’t matter how old he is (a), or Lauren’s initial amount (Y), as long as Y ≥ 2a ≥ 40, then John will end up with twice the amount in the reverse scenario.

      For example: X = 114, Y = 62, a = 25.

      actual:
      start: J=114, L=62
      (57+19) J→L: J=38, L=138
      (69+25) J→L: J=132, L=44

      reverse:
      start: J=114, L=62
      (31+25) L→J: J=170, L=6
      (85+19) J→L: J=66, L=110

      And 132 = 2×66.

      Like

  • Unknown's avatar

    Jim Randell 7:30 am on 15 February 2026 Permalink | Reply
    Tags:   

    Teaser 3308: New towns 

    From The Sunday Times, 15th February 2026 [link] [link]

    Three new towns (A, B and C) were being built, with straight roads joining them. Each road was a whole number of miles in length, with AB the same as BC and a total length of the three roads of 108 miles.

    A new power station was needed for the three towns and two plans were considered. The Plan 1 site at point P was to be the same distance from each town (a perfect square number of miles). The Plan 2 site was to be a whole number of miles along PB such that the total length of cable connecting the power station to each town was a whole number of miles. Given the above, no shorter total cable length of a whole number of miles was possible, so plan 2 was adopted.

    What was the total cable length?

    [teaser3308]

     
    • Jim Randell's avatar

      Jim Randell 9:00 am on 15 February 2026 Permalink | Reply

      This Python program runs in 73ms. (Internal runtime is 291µs).

      from enigma import (Accumulator, irange, is_triangle, rcs, fdiv, is_square_p, point_dist, intr, printf)
      
      # if float <f> is within <t> of integer <i> return <i>
      def snapf(f, t=1e-6):
        i = intr(f)
        if abs(i - f) < t: return i
      
      T = 108  # T = AB + BC + AC
      # choose a value for x (= AB = BC)
      for x in irange(1, (T - 1) // 2):
        # calculate y (= AC)
        y = T - 2*x
        if not is_triangle(x, x, y): continue
        # calculate the positions of the towns
        z = 0.5 * y
        h = rcs(x, -z)
        (A, B, C) = ((z, 0), (0, h), (-z, 0))
      
        # P = (0, h - p) is the circumcentre of triangle ABC
        # distance p = BP must be an integer (and a perfect square)
        p = snapf(fdiv(x * x, 2 * h))
        if not is_square_p(p): continue
        printf("x={x} y={y} -> h={h} p={p} [A={A} B={B} C={C}]")
      
        # find minimum total length of cable
        r = Accumulator(fn=min, collect=1)
      
        # choose a distance along BP (excluding endpoints) to site Q
        for d in irange(1, p - 1):
          # calculate total length of cable required
          Q = (0, h - d)
          ds = list(snapf(point_dist(Q, X)) for X in [A, B, C])
          # distance to each town is an integer
          if None in ds: continue
          t = sum(ds)
          # output scenario
          printf("-> d={d} Q={Q} ds={ds} t={t}")
          r.accumulate_data(t, d)
      
        # output minimal length
        printf("minimal length = {r.value} [d={r.data}]")
        printf()
      

      Solution: [To Be Revealed]

      [diagram to follow]

      Like

    • Frits's avatar

      Frits 8:09 am on 16 February 2026 Permalink | Reply

      Based on Jim’s program.
      Good chance I don’t understand anymore if I will look at it at a later date.

      I didn’t check if Plan 2 used a shorter total cable length then Plan 1.

      from enigma import is_square, ceil
      
      # distance metric between 2 points
      dist = lambda p, q: ((p[0] - q[0])**2 + (p[1] - q[1])**2)**.5
      
      sol = 99999
      # choose a value for x (= AB = BC), y < 2x so 4x > 108
      for x in range(28, 54):
        # calculate y (= AC)
        y = 108 - 2 * x
        
        # calculate height (line B perpendicular to AC)
        h = 6 * (3 * x - 81)**.5
        # calculate the distance p = BP
        p, r = divmod(x**2, 2 * h)
        if r or not is_square(p): continue
        
        A = (y // 2, 0)
        # derive points that are an integer distance away from point A
        sol = min(sol, min(2 * sq + h - n for n in range(ceil(h)) 
                           if (sq := is_square((54 - x)**2 + n**2))))
          
      print(f"minimal length = {sol}")
      

      Like

      • Jim Randell's avatar

        Jim Randell 11:56 am on 16 February 2026 Permalink | Reply

        @Frits: This doesn’t seem to check all integer points along PB (there should be p − 1 of them, if we exclude the endpoints).

        Like

        • Frits's avatar

          Frits 4:33 pm on 16 February 2026 Permalink | Reply

          @Jim, my code is not totally correct.

          I had noticed that the distances from Q to A and Q to C in the optimal solution were symmetrical around d=h (fi these distances were the same
          for d=h-1 and d=h+1). The distance from Q to B is not symmetrical around d=h but is increasing. This means that if d > h potential new total length of cable will always be higher than the other symmetrical value (at least if p <= 2.h).

          That's why I took a shortcut to check fewer entries. That is not always allowed.

          Like

          • Jim Randell's avatar

            Jim Randell 8:07 am on 17 February 2026 Permalink | Reply

            @Frits: Fair enough (although does that not assume the intersection of AC and BP is a (half-) integer distance from B and P – is this justified in general?). It just wasn’t clear to me from the code you posted that all possible positions would be considered.

            Like

    • Alex.T.Sutherland's avatar

      Alex.T.Sutherland 2:32 pm on 18 February 2026 Permalink | Reply

      Given:- Towns form an isosceles triangle AB = a; BC = a; AC = b;
      Periphery = 2*a + b = 108. b is even;
      Plan 1. P is the centre of the circumsbribed circle thro’the towns
      and R is the radius (a perfect square ).
      The line PB halves AC at D and is perpendicular to AC.
      P is distant R from B in the appropriate direction.

      Soln:- Using R = a^2 / ( sqrt(4*(a^2) -b^2).
      2*a+b = 108.
      R is a perfect square.
      Solve for R,a,b
      (Since b is even use it instead of ‘a’..less nuumber of calcs).
      This gives R,a,b,and the postion of P.
      The total cable length in Plan 1 = 3*R.
      P = site location for Plan 1.

      S is the site location on line PB ,integer from P distant x = [1:R] .
      For each x calculate Length = 2*AS + BS;
      Find integer pairs (x Lx).(I have found 4 such pairs…one is S=B ie x= R).
      There are 2 with a minimum length (B being one of them).
      The answer is either one.
      This does not affect the required answer only where the site is to be located.

      Answer: Significantly less than Plan_1 which is 3*R.
      Lots of Pythagorean triangles.
      Sum of the digits for each of [AS BS CS] are all equal.
      (as is the digit product of b/2).

      Time :- Aprox. 0.5 ms

      Like

  • Unknown's avatar

    Jim Randell 8:15 am on 13 February 2026 Permalink | Reply
    Tags:   

    Teaser 2458: [Chocolate cylinders] 

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

    Willy took a cylindrical cake of radius a whole prime number of millimetres. He coated the curved surface with a layer of chocolate an odd prime number of millimetres thick and let it set. He repeated this a few times, building up layers of the same thickness. Being a silly Willy, he then left the cake in the sun and all the chocolate melted. So he used it to make nine solid cylinders of chocolate, each of radius 20 mm and length the same as the original cake.

    How many layers of chocolate did he apply to the cake?

    This puzzle was originally published with no title.

    [teaser2458]

     
    • Jim Randell's avatar

      Jim Randell 8:15 am on 13 February 2026 Permalink | Reply

      Suppose the cake has radius r and height h.

      Then, if n layers of chocolate, each of thickness t, are added, the total volume of chocolate used is:

      V = 𝝅 (r + n.t)^2 h − 𝝅 r^2 h

      And this same volume can also be used to make 9 solid cylinders of chocolate, each with a radius of 20 mm:

      V = 9 𝝅 20^2 h

      Hence:

      𝝅 (r + n.t)^2 h − 𝝅 r^2 h = 9 𝝅 20^2 h
      (r + n.t)^2 − r^2 = 60^2

      The LHS is the difference of 2 squares, so can be rewritten:

      (n.t)(2r + n.t) = 60^2

      So we can solve the puzzle by looking at the divisors of 60^2.

      The following Python program runs in 68ms. (Internal runtime is 96µs).

      from enigma import (divisors_pairs, div, is_prime, printf)
      
      # consider divisors of 3600
      for (a, b) in divisors_pairs(60, 2):
        r = div(b - a, 2)
        if r is None or not is_prime(r): continue
      
        printf("r={r} [nt={a}]")
        for (n, t) in divisors_pairs(a, every=1):
          if not (t % 2 == 1 and is_prime(t)): continue
          printf("-> n={n} t={t}")
      

      Solution: Willy applied 10 layers of chocolate to the cake.

      The situation is apparently:

      cake radius = 11 mm
      layer thickness = 5 mm
      number of layers = 10

      So the cake is only 22 mm across, and it was then coated with 10 layers of 5 mm chocolate. Which means the finished item was 122 mm across with only a tiny 22 mm centre consisting of cake.

      Like

    • Ruud's avatar

      Ruud 9:48 am on 13 February 2026 Permalink | Reply

      import peek
      import istr
      
      for r, d, n in istr.product(istr.primes(1000), istr.primes(3, 1000), range(2, 20)):
          if (r + n * d) ** 2 - r**2 == 9 * (20**2):
              peek(r, n, d)
      

      Like

  • Unknown's avatar

    Jim Randell 9:43 am on 10 February 2026 Permalink | Reply
    Tags:   

    Teaser 2333: [Continuous ledger] 

    From The Sunday Times, 10th June 2007 [link]

    The firm I work for has kept a ledger since its foundation. One fresh page is used each day, and these pages have been numbered consecutively since the firm was founded. During a weekend last year I noticed that the page number was a perfect square. Then, during a weekend earlier this year, I noticed that the page number was a perfect cube. On another day earlier that month, I had noticed that the page number was a perfect fourth power.

    When will the number next be palindromic?

    This puzzle was originally published with no title.

    There are now 1300 Teaser puzzles available on the site — which is 25 years worth of weekly puzzles. (And between S2T2 and Enigmatic Code there are 3866 puzzles available in total).

    [teaser2333]

     
    • Jim Randell's avatar

      Jim Randell 9:44 am on 10 February 2026 Permalink | Reply

      You need to take into account the date the puzzle was originally published when solving this puzzle.

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

      from datetime import (date, timedelta)
      from enigma import (powers, inf, first, le, repeat, inc, peek, irange, is_npalindrome, printf)
      
      # date of puzzle (all dates must be earlier than this)
      pub = date(2007, 6, 10)
      
      # consider numbers up to 200_000
      (sqs, cbs, p4s) = (first(powers(1, inf, k), count=le(200000)) for k in [2, 3, 4])
      
      # is a date a weekend (= Saturday (6) or Sunday (7))
      is_weekend = lambda d: d.isoweekday() in {6, 7}
      
      # consider powers of 4
      for p4 in p4s:
      
        # look for a higher cube, potentially within the same month
        for cb in reversed(cbs):
          if not (cb > p4): break
          if cb - p4 > 30: continue
      
          # consider possible dates for the cube in the current year (before publication)
          for dcb in repeat(inc(timedelta(days=-1)), pub):
            if dcb.year < pub.year: break
            # must be on a weekend
            if not is_weekend(dcb): continue
            # calculate date for the power of 4
            dp4 = dcb - timedelta(days=cb - p4)
            # must be in the same month
            if not (dp4.month == dcb.month): continue
      
            # look for earlier perfect squares
            for sq in sqs:
              if not (sq < p4): break
              # calculate date for the square
              dsq = dp4 - timedelta(days=p4 - sq)
              y = dp4.year - dsq.year
              if not (0 < y < 2): continue
              # must be on a weekend
              if not is_weekend(dsq): continue
      
              # when is the next palindromic date (after cb)
              pl = peek(n for n in irange(cb + 1, inf) if is_npalindrome(n))
              dpl = dp4 + timedelta(days=pl - p4)
      
              # calculate founding date
              df = dp4 - timedelta(days=p4 - 1)
      
              # output solution
              printf("p4 = D{p4} = {dp4}; cb = D{cb} = {dcb}; sq = D{sq} = {dsq}; pl = D{pl} = {dpl}; D1 = {df}")
      

      Solution: The next palindromic number will occur on 20th June 2007.

      The square number is day 50176 (= 224^2) on 2006-01-07 (Saturday).

      The perfect cube is day 50653 (= 37^3) on 2007-04-29 (Sunday).

      The power of 4 is day 50625 (= 15^4) on 2007-04-01 (Sunday).

      And the next palindromic number after 50653 is 50705 on 2007-06-20 (Wednesday), i.e. 10 days after the puzzle was published.

      If the ledger has been in continual operation from the day of founding, then day 1 was 1868-08-23 (Sunday).

      Like

  • Unknown's avatar

    Jim Randell 7:12 am on 8 February 2026 Permalink | Reply
    Tags:   

    Teaser 3307: A dish best served cold 

    From The Sunday Times, 8th February 2026 [link] [link]

    King Otto’s birthday cake was a giant mousse. Its tiers were two concentric regular octagons. The upper tier’s span equalled the lower tier’s side-length (the diagrams show top and side views). Each tier’s height equalled the base tier octagon’s side-length (a two-figure whole number of inches under 20) divided by the square root of two (chef used a 45 degree right triangle gauge for this). When all tables at the party (arranged in three equal lines) were fully occupied (each set for the same number of couples) each person got an identical portion of eight cubic inches of cake (not necessarily in the shape of a cube). The small amount left over was less than this.

    How many tables were there?

    [teaser3307]

     
    • Jim Randell's avatar

      Jim Randell 7:57 am on 8 February 2026 Permalink | Reply

      (See also: Teaser 2976, Teaser 2921).

      This Python program considers possible side lengths of the octagonal lower tier, calculates the total volume of both tiers, and then divides it into 8 cu in portions.

      The number of portions is then allocated to three equal rows of tables, with the same number of guests at each table. (I allowed between 2 and 20 couples at each table, which gives a single answer).

      It runs in 70ms. (Internal runtime is 87µs).

      from enigma import (irange, sqrt, fdiv, intr, div, divisors_pairs, printf)
      
      r2 = sqrt(2)
      
      # area of an octagon with side x
      area = lambda x: 2 * x * x * (1 + r2)
      
      # consider possible side lengths of the larger octagon = x (2-digit numbers less than 20)
      for x in irange(10, 19):
        # calculate the height of the tiers = h
        h = fdiv(x, r2)
        # volume of the lower tier
        V1 = area(x) * h
        # volume of the upper tier
        z = fdiv(x, 1 + r2)
        V2 = area(z) * h
        # total volume of the cake (to the nearest cu in)
        V = intr(V1 + V2)
      
        # divide into portions = k; remainder = r
        (k, r) = divmod(V, 8)
        # there is a small amount remaining
        if r == 0: continue
        # there are 3 rows of tables, and some couples on each table
        p = div(k, 6)
        if p is None: continue
        # each seating the same number of couples = a, with tables per row = b
        for (a, b) in divisors_pairs(p, every=1):
          if not (a > 1): continue  # more than 1 couple per table
          if a > 20: break  # but no more than 20
          # output scenario
          printf("x={x} h={h:.2f} -> V={V} k={k} r={r}")
          printf("-> 3 rows of: {p} portions = {a} couples on {b} tables", p=2*p)
          printf("--> total tables = {T}", T=3*b)
          printf()
      

      Solution: There were 183 tables.

      The tables are arranged in 3 rows, each with 61 tables, and each table seats 3 couples (= 6 guests), for a total of 1098 guests, which requires 8784 cu in of cake.

      The lower tier of the cake has side length of 13 in, which makes the total volume of the cake 8788 cu in (leaving 4 cu in left over).

      Without restrictions on the number of guests at each table we could seat 1098 guests using:

      3 rows, each with 1 table, and each table seats 183 couples (366 guests)
      3 rows, each with 3 tables, and each table seats 61 couples (122 guests)
      3 rows, each with 61 tables, and each table seats 3 couples (6 guests)
      3 rows, each with 183 tables, and each table seats 1 couple (2 guests)

      I decided to keep the tables a manageable size with 3 couples (= 6 guests) at each table.

      But perhaps it would have been better if the total number of guests had been asked for (or the allowable number of guests per table specified).


      If you determine the total volume of cake in terms of x (or let Wolfram Alpha determine it for you [ link ]), you will find:

      V = 4 x^3

      Which can be used instead of lines 10-18 to directly to calculate the volume of the cake (without using floating point approximations).

      And can also be used in a manual solution, as follows:

      We see that for even x the volume will be an exact multiple of 8, and there will be no unused portion, so we can consider odd values for x, and calculate V (which will have leave a remainder of 4 cu in). The number of portions p must then be divisible by 6 (for each couple in each of the 3 rows).

      x = 11: V = 5324 = 665×8 + 4; p/6 = 110.83…
      x = 13: V = 8788 = 1098×8 + 4; p/6 = 183
      x = 15: V = 13500 = 1687×8 + 4; p/6 = 281.16…
      x = 17: V = 19652 = 2456×8 + 4; p/6 = 409.33…
      x = 19: V = 27436 = 3429×8 + 4; p/6 = 571.5

      Only x = 13, gives a viable number of portions. And we can further split 183 to give the four candidate scenarios given above:

      183 = 183×1 → 3 rows, each with 183 tables, and each table seats 1 couple (2 guests)
      183 = 61×3 → 3 rows, each with 61 tables, and each table seats 3 couples (6 guests)
      183 = 3×61 → 3 rows, each with 3 tables, and each table seats 61 couples (122 guests)
      183 = 1×183 → 3 rows, each with 1 table, and each table seats 183 couples (366 guests)

      Of these the first seems unlikely (1 couple per table), and we can reduce the remaining three to a single candidate by placing an upper limit (of 120 or fewer) on the number of guests per table.

      Giving a solution of 3 rows, each with 61 tables, so 183 tables tables in total.

      Like

      • Jim Randell's avatar

        Jim Randell 10:55 am on 17 February 2026 Permalink | Reply

        If you don’t want to do the analysis yourself (or let Wolfram Alpha do it), and you don’t want to wheel out the big guns (like SymPy), then the following class allows you to do simple arithmetic operations involving an irrational number.

        from enigma import enigma
        
        Q = enigma.Rational()
        
        # manipulate numbers of the form: a + b*sqrt(n) where n is an integer, and a and b are rational
        class Surd(object):
        
          def __init__(self, n, a=0, b=1):
            self.n = n
            self.a = a
            self.b = b
        
          def __repr__(self):
            return str.format("Surd[{a} + {b}*sqrt({n})]", a=self.a, b=self.b, n=self.n)
        
          # evaluate to a standard numeric type (you might get a float, or a complex, or a Q object)
          def val(self):
            (n, a, b) = (self.n, self.a, self.b)
            return (a if b == 0 else a + b * n**0.5)
        
          # extract (n, a, b, c, d) parameters
          def _params(self, other):
            if not isinstance(other, Surd): other = Surd(self.n, other, 0)
            if not (self.n == other.n): raise ValueError("Surd: incompatible values")
            return (self.n, self.a, self.b, other.a, other.b)
        
          # calculate self + other
          def __add__(self, other):
            (n, a, b, c, d) = self._params(other)
            return Surd(n, a + c, b + d)
        
          __radd__ = __add__
        
          def __neg__(self):
            return Surd(self.n, -self.a, -self.b)
        
          def __sub__(self, other):
            (n, a, b, c, d) = self._params(other)
            return Surd(n, a - c, b - d)
        
          __rsub__ = lambda self, other: -self + other
        
          # calculate self * other
          def __mul__(self, other):
            (n, a, b, c, d) = self._params(other)
            return Surd(n, a * c + b * d * n, a * d + b * c)
        
          __rmul__ = __mul__
        
          # calculate self / other
          def __truediv__(self, other):
            (n, a, b, c, d) = self._params(other)
            D = c * c - d * d * n
            return Surd(n, Q(a * c - b * d * n, D), Q(b * c - a * d, D))
        
          def __rtruediv__(self, other):
            if not isinstance(other, Surd): other = Surd(self.n, other, 0)
            return other.__truediv__(self)
        
          # Python 2 support
          __div__ = __truediv__
          __rdiv__ = __rtruediv__
        

        My program can then be modified to use this class, and we find that the irrational falls out of the expression and always leaves us with an exact integer volume for the cake.

        from enigma import (irange, as_int, div, divisors_pairs, printf)
        
        # representation of sqrt(2)
        r2 = Surd(2)
        
        # area of an octagon with side x
        area = lambda x: 2 * x * x * (1 + r2)
        
        # consider possible side lengths of the larger octagon = x (2-digit numbers less than 20)
        for x in irange(10, 19):
          # calculate the height of the tiers = h
          h = x / r2
          # volume of the lower tier
          V1 = area(x) * h
          # volume of the upper tier
          z = x / (1 + r2)
          V2 = area(z) * h
          # total volume of the cake
          V = V1 + V2
          # retrieve the actual numeric value
          V = as_int(V.val())
        
          # divide into portions = k; remainder = r
          (k, r) = divmod(V, 8)
          # there is a small amount remaining
          if r == 0: continue
          # there are 3 rows of tables, and some couples on each table
          p = div(k, 6)
          if p is None: continue
          # each seating the same number of couples = a, with tables per row = b
          for (a, b) in divisors_pairs(p, every=1):
            if not (a > 1): continue  # more than 1 couple per table
            if a > 20: break  # but no more than 20
            # output scenario
            printf("x={x} h={h:.2f} -> V={V} k={k} r={r}", h=float(h.val()))
            printf("-> 3 rows of: {p} portions = {a} couples on {b} tables", p=2*p)
            printf("--> total tables = {T}", T=3*b)
            printf()
        

        Like

  • Unknown's avatar

    Jim Randell 8:39 am on 6 February 2026 Permalink | Reply
    Tags:   

    Teaser 2459: [Queue for tea] 

    From The Sunday Times, 8th November 2009 [link]

    At today’s tea break only one of the six workers in the canteen queue actually had tea, the other five having different drinks. Terry was directly behind the one who had hot chocolate, while Tony (who was not at the front of the queue) was immediately in front of the sparkling-water drinker (who was not Terry). The milk drinker was three places in front of the person who had white coffee. Tilly was directly behind Tommy. Timmy was two places ahead of the hot-chocolate drinker. The person at the front of the queue had black coffee.

    Who had tea? And where was Trudy in the queue?

    This puzzle was originally published with no title.

    [teaser2459]

     
    • Jim Randell's avatar

      Jim Randell 8:41 am on 6 February 2026 Permalink | Reply

      Here is a solution using the [[ SubstitutedExpression ]] solver from the enigma.py library.

      The following run file executes in 79ms. (Internal runtime of the generated code is 87µs).

      #! python3 -m enigma -rr
      
      SubstitutedExpression
      
      # we assign queue positions 1 (= front) to 6 (= back)
      --digits="1-6"
      --macro="@Terry = A"
      --macro="@Tony = B"
      --macro="@Tilly = C"
      --macro="@Tommy = D"
      --macro="@Timmy = E"
      --macro="@Trudy = F"
      --macro="@Te = G"  # Tea
      --macro="@HC = H"  # Hot Chocolate
      --macro="@SW = I"  # Sparkling Water
      --macro="@Mk = J"  # Milk
      --macro="@WC = K"  # White Coffee
      --macro="@BC = L"  # Black Coffee
      --distinct="ABCDEF,GHIJKL"
      
      # "Terry was directly behind Hot Chocolate"
      "@HC + 1 = @Terry"
      
      # "Tony (who is not at the front of the queue) ..."
      "@Tony > 1"
      # "... was immediately in front of Sparkling Water ..."
      "@SW - 1 = @Tony"
      # "... (who was not Terry)"
      "@SW != @Terry"
      
      # "Milk was 3 places in front of White Coffee"
      "@WC - 3 = @Mk"
      
      # "Tilly was directly behind Tommy"
      "@Tommy + 1 = @Tilly"
      
      # "Timmy was 2 places ahead of Hot Chocolate"
      "@HC - 2 = @Timmy"
      
      # "The person at the front of the queue had Black Coffee"
      "@BC = 1"
      
      --template="(A B C D E F) (G H I J K L)"
      --solution=""
      --verbose="1-W"
      

      And here is a Python program that runs the solver, and then formats the output nicely:

      from enigma import (SubstitutedExpression, irange, printf)
      
      # load the puzzle
      p = SubstitutedExpression.from_file(["{dir}/teaser2459.run"])
      
      # link symbols to values
      s2n = dict(A='Terry', B='Tony', C='Tilly', D='Tommy', E='Timmy', F='Trudy')
      s2d = dict(G='tea', H='hot chocolate', I='sparkling water', J='milk', K='white coffee', L='black coffee')
      
      # solve the puzzle and format solutions
      for s in p.solve(verbose="0"):
        # for each position 1-6 fill out a corresponding name and drink
        (name, drink) = (dict((s[k], v) for (k, v) in m.items()) for m in (s2n, s2d))
        # output the queue
        for i in irange(1, 6):
          (n, d) = (m.get(i, '???') for m in (name, drink))
          printf("{i}: {n}, {d}")
        printf()
      

      Solution: Terry had tea. Trudy was 6th in the queue.

      The positions in the queue and drinks required are:

      1: Timmy, black coffee
      2: Tommy, milk
      3: Tilly, hot chocolate
      4: Terry, tea
      5: Tony, white coffee
      6: Trudy, sparkling water

      Like

  • Unknown's avatar

    Jim Randell 9:34 am on 3 February 2026 Permalink | Reply
    Tags: ,   

    Teaser 2461: [Football league] 

    From The Sunday Times, 22nd November 2009 [link]

    The saying “Most teams lose most of the time” was true of our league last season. Five teams, Albion, Broncos, City, Devils and Eagles, play each other once, earning three points for a win, one for a draw. Albion won and the teams ended in alphabetical order, the positions of teams tying on points determined by goal difference. Albion’s goal difference was four times the Broncos’. No match scores were the same; 32 goals were scored; City scored none against Albion; and Devils scored four different consecutive numbers of goals.

    What were the scores in the four Devils’ games (DvA, DvB, DvC, DvE)?

    Although this puzzle can be solved there are two possible answers (although only one of them was given when the solution was published in The Sunday Times).

    This puzzle was originally published with no title.

    [teaser2461]

     
    • Jim Randell's avatar

      Jim Randell 9:35 am on 3 February 2026 Permalink | Reply

      There are 5 teams in the league, so each team plays 4 matches. For a team to “lose most of the time”, they would have to lose at least 3 of their 4 matches. And for “most teams to lose most of the time”, there have to be at least 3 teams that lost at least 3 of their matches.

      So, of the 10 matches in the tournament, at least 9 of them must be lost/won, i.e. there can be at most 1 drawn match.

      All the scores in the matches must be different, so in increasing numbers of total goals scored in lost/won match we have the possible following scorelines:

      1: 1-0
      2: 2-0
      3: 3-0, 2-1
      4: 4-0, 3-1
      5: 5-0, 4-1, 3-2

      At this point, we have identified 9 matches, and the total number of goals scored in them is 32. So all these must take place, and the remaining match must be a 0-0 draw. And we have identified the scores in all of the 10 matches.

      This Python program allocates the scores to the matches. It runs in 20s (using PyPy).

      from enigma import (Football, subsets, diff, cproduct, ordered, is_consecutive, printf)
      
      # scoring system
      football = Football(games="wdl", points=dict(w=3, d=1))
      
      # scores in the 10 matches; all different, and 32 goals scored in total
      scores = [(1, 0), (2, 0), (3, 0), (2, 1), (4, 0), (3, 1), (5, 0), (4, 1), (3, 2), (0, 0)]
      assert sum(x + y for (x, y) in scores) == 32
      
      # allocate <k> scores from <scs>
      def allocate(k, scs):
        for ss in subsets(scs, size=k, select='P'):
          rs = diff(scs, ss)
          for xys in cproduct({(x, y), (y, x)} for (x, y) in ss):
            yield (xys, rs)
      
      # calculate the table and goal difference from a sequence of scores
      def table(ss, ts):
        T = football.table(football.outcomes(ss), ts)
        (f, a) = football.goals(ss, ts)
        return (T, f - a)
      
      # X did better than Y
      def better(ptsX, ptsY, gdX, gdY):
        return ptsX > ptsY or (ptsX == ptsY and gdX > gdY)
      
      # choose the scores in D's matches
      for ((AD, BD, CD, DE), scs1) in allocate(4, scores):
        # D's goals in each match must be consecutive (in some order)
        if not is_consecutive(ordered(AD[1], BD[1], CD[1], DE[0])): continue
        # calculate the table for D
        (D, gdD) = table([AD, BD, CD, DE], [1, 1, 1, 0])
      
        # choose the scores in C's matches
        for ((AC, BC, CE), scs2) in allocate(3, scs1):
          # C scored 0 goals in the A v C match
          if not (AC[1] == 0): continue
          # calculate the table for C
          (C, gdC) = table([AC, BC, CD, CE], [1, 1, 0, 0])
          # C did better than D
          if not better(C.points, D.points, gdC, gdD): continue
      
          # choose the scores in B's matches
          for ((AB, BE), scs3) in allocate(2, scs2):
            # calculate the table for B
            (B, gdB) = table([AB, BC, BD, BE], [1, 0, 0, 0])
            # B did better than C
            if not better(B.points, C.points, gdB, gdC): continue
      
            # allocate the remaining match
            for ([AE], _) in allocate(1, scs3):
              # calculate the table for A
              (A, gdA) = table([AB, AC, AD, AE], [0, 0, 0, 0])
              # A did better than B
              if not better(A.points, B.points, gdA, gdB): continue
              # A's goal difference is 4 times B's
              if not (gdA == 4 * gdB): continue
      
              # calculate the table for E
              (E, gdE) = table([AE, BE, CE, DE], [1, 1, 1, 1])
              # D is higher than E
              if not better(D.points, E.points, gdD, gdE): continue
      
              # at least 3 teams lost at least 3 matches
              if not sum(X.l >= 3 for X in [A, B, C, D, E]) >= 3: continue
      
              # output scenario
              printf("AB={AB} AC={AC} AD={AD} AE={AE} BC={BC} BD={BD} BE={BE} CD={CD} CE={CE} DE={DE}")
              printf("A={A} gd={gdA}")
              printf("B={B} gd={gdB}")
              printf("C={C} gd={gdC}")
              printf("D={D} gd={gdD}")
              printf("E={E} gd={gdE}")
              printf()
      

      Solution: There are two possible answers:

      DvA = 0-3; DvB = 2-3; DvC = 1-4; DvE = 3-1
      DvA = 1-4; DvB = 2-3; DvC = 0-3; DvE = 3-1

      Only the first of these was given in the published solution.

      These correspond to the following 4 scenarios:

      AvB = 0-0; AvC = 4-0; AvD = 3-0; AvE = 5-0; BvC = 2-1; BvD = 3-2; BvE = 1-0; CvD = 4-1; CvE = 0-2; DvE = 3-1
      AvB = 0-0; AvC = 4-0; AvD = 3-0; AvE = 5-0; BvC = 1-0; BvD = 3-2; BvE = 2-1; CvD = 4-1; CvE = 0-2; DvE = 3-1
      AvB = 0-0; AvC = 4-0; AvD = 4-1; AvE = 5-0; BvC = 2-1; BvD = 3-2; BvE = 1-0; CvD = 3-0; CvE = 0-2; DvE = 3-1
      AvB = 0-0; AvC = 4-0; AvD = 4-1; AvE = 5-0; BvC = 1-0; BvD = 3-2; BvE = 2-1; CvD = 3-0; CvE = 0-2; DvE = 3-1

      i.e. the order of {AvD, CvD} = {3-0, 4-1} and {BvC, BvE} = {2-1, 1-0} is not determined.

      But in each case the final table is:

      1st: A → 3w1d = 10 points; goal diff = 12
      2nd: B → 3w1d = 10 points; goal diff = 3
      3rd: C → 1w3l = 3 points; goal diff = −4
      4th: D → 1w3l = 3 points; goal diff = −5
      5th: E → 1w3l = 3 points; goal diff = −6

      With teams C, D, E (i.e. “most teams”) having lost 3 of their matches (i.e. “lost most of the time”).

      Like

  • Unknown's avatar

    Jim Randell 6:53 am on 1 February 2026 Permalink | Reply
    Tags:   

    Teaser 3306: Pin-up 

    From The Sunday Times, 1st February 2026 [link] [link]

    Over the years I have used seven different PINs. The first consisted of a four-digit number (the first digit not being zero), and thereafter each new PIN was obtained by swapping over two of the digits of the previous PIN; each time this increased the PIN.

    The first PIN (not surprisingly!) was divisible by 1, the second was divisible by 2, the third by 3, and so on, with the seventh divisible by 7 (in fact the seventh PIN was the only one divisible by 7).

    What was the third PIN?

    [teaser3306]

     
    • Jim Randell's avatar

      Jim Randell 7:06 am on 1 February 2026 Permalink | Reply

      It is quicker (and neater) to build the list in reverse order. We can start with a final PIN that is a multiple of 7 (and 3), and then work backwards, undoing the swaps, to get back to the initial PIN.

      This Python program runs in 76ms. (Internal runtime is 6.8ms).

      from enigma import (irange, subsets, nsplit, nconcat, swap, printf)
      
      # generate possible swaps by index (on a 4-digit sequence)
      swap_inds = list(subsets(irange(4), size=2))
      
      # solve the puzzle for a sequence of (<number>, <digit>) pairs
      # at each stage finding the _previous_ PIN
      def _solve(ss):
        k = len(ss)
        # are we done?
        if k == 7:
          yield ss
        else:
          (n, ds) = ss[0]
          # swap 2 digits of the following PIN
          for (i, j) in swap_inds:
            ds1 = swap(ds, i, j)
            # no leading zeros
            if ds1[0] == 0: continue
            n1 = nconcat(ds1)
            # previous PINs must be: smaller; not be divisible by 7; divisible by their position
            if n1 < n and n1 % 7 > 0 and n1 % (7 - k) == 0:
              yield from _solve([(n1, ds1)] + ss)
      
      # solve the puzzle for final PIN <n>
      def solve(n):
        # final PIN is divisible by 7
        if n % 7 > 0: return
        # find previous PINs
        for ss in _solve([(n, nsplit(n))]):
          # return the list of numbers
          yield tuple(n for (n, ds) in ss)
      
      # consider the final PIN (divisible by 7 (and 3))
      for n in irange.round(1000, 9999, step=21, rnd='I'):
        for ns in solve(n):
          printf("{ns}")
      

      Solution: The third PIN is 5286.

      There are 2 possible sequences of PINs that differ at the second PIN:

      2568 → {2586, 5268} → 5286 → 8256 → 8265 → 8562 → 8652

      Like

      • Ruud's avatar

        Ruud 11:19 am on 1 February 2026 Permalink | Reply

        How do you know that the final PIN does not start with 0 ?

        Like

        • Jim Randell's avatar

          Jim Randell 11:47 am on 1 February 2026 Permalink | Reply

          @Ruud: The first PIN has no leading zero, so is greater than 999. And each subsequent PIN is larger than the one preceding it, so all the PINs are greater than 999, hence none of them have a leading zero.

          Like

      • ruudvanderham's avatar

        ruudvanderham 11:27 am on 1 February 2026 Permalink | Reply

        Ah, I see: because it has to be greater than the first PIN, which is >=1000 .
        But, how do you know that the final PIN is divisible by 3?

        Like

        • Jim Randell's avatar

          Jim Randell 11:48 am on 1 February 2026 Permalink | Reply

          @Ruud: If a number is divisible by 3 than any number formed from a rearrangement of the digits is also divisible by 3. Hence all the PINs must be divisible by 3.

          So if the final PIN is divisible by both 7 and 3, then it must be divisible by 21 (= LCM(7, 3)).

          Like

    • Ruud's avatar

      Ruud 9:34 am on 1 February 2026 Permalink | Reply

      import istr
      
      
      def solve(pins):
          for i0, i1 in istr.combinations(range(4), r=2):
              n = len(pins) + 1
              pin = istr.join(pins[-1][int(i0)] if i == i1 else pins[-1][int(i1)] if i == i0 else pins[-1][i] for i in range(4))
              if pin > pins[-1] and pin.is_divisible_by(n):
                  if n == 7:
                      yield pins + [pin]
                  elif not pin.is_divisible_by(7):
                      yield from solve(pins + [pin])
      
      
      for pin in istr(range(1000,10000)):
          for pins in solve([pin]):
              print(pins)

      Like

    • Frits's avatar

      Frits 1:32 pm on 1 February 2026 Permalink | Reply

      from itertools import combinations
      
      # generate and check the k-th PIN (decreasing k)
      def check(s, k):
        if not k:
          yield int(''.join(s[4]))      # third PIN
        else:
          # swap 2 digits
          for i, j in combinations(range(4), 2):
            # swap should result in a lower number > 999
            if s[-1][i] <= s[-1][j] or (i == 0 and s[-1][j] == "0"): continue
            new = [s[-1][j] if y == i else s[-1][i] if y == j else s[-1][y]
                 for y in range(4)]  
            # the seventh PIN was the only one divisible by 7
            if (n := int(''.join(new))) % k == 0 and n % 7: 
              yield from check(s + [new], k - 1)       
      
      sols = set()
      # first possible seventh PIN divisible by 21 (div 7, div 3)
      f = next(i for i in range(2001, 2024, 3) if i % 7 == 0)
      
      for p7 in range(f, 10000, 21):
        # div 5 case
        if "5" in (s := str(p7)):
          # we need an even digit for the div 4 case
          if set("02468").isdisjoint(s): continue
        elif "0" in s:
          # we need at least 2 even digits for the div 4 case 
          if sum(int(x) % 2 for x in s) > 2: continue
        else: 
          continue  
          
        # we need at least 7 different permutations  
        if len(set(s)) < 3: continue
        
        # generate all PINs and store the third PIN
        for p3 in check([s], 6):
          sols.add(p3)
          
      print(f"answer: {' or '.join(str(s) for s in sols)}")    
      

      Like

    • Ruud's avatar

      Ruud 5:43 am on 2 February 2026 Permalink | Reply

      ChatGPT solved it in 47 seconds:

      from itertools import permutations, combinations
      
      def swaps(a, b):
          """Return True if b can be obtained from a by swapping exactly two digits."""
          diffs = [i for i in range(4) if a[i] != b[i]]
          return len(diffs) == 2 and a[diffs[0]] == b[diffs[1]] and a[diffs[1]] == b[diffs[0]]
      
      def valid_chain(chain):
          """Check divisibility, increasing order, and swap condition."""
          for i in range(7):
              if chain[i] % (i+1) != 0:
                  return False
              if i > 0:
                  if chain[i] <= chain[i-1]:
                      return False
                  if not swaps(str(chain[i-1]), str(chain[i])):
                      return False
          # only the 7th is divisible by 7
          return all(chain[i] % 7 != 0 for i in range(6))
      
      solutions = []
      
      # choose 4 distinct digits, first not zero
      digits = [str(d) for d in range(10)]
      
      for digs in combinations(digits, 4):
          for perm in permutations(digs):
              if perm[0] == "0":
                  continue
              nums = sorted(
                  int("".join(p)) for p in permutations(perm) if p[0] != "0"
              )
              for chain in permutations(nums, 7):
                  if valid_chain(chain):
                      solutions.append(chain)
      
      # print solutions and the third PIN
      for sol in solutions:
          print(sol, "→ third PIN:", sol[2])
      

      Scary …

      Like

      • Ruud's avatar

        Ruud 6:10 am on 2 February 2026 Permalink | Reply

        Maybe less scary than I thought.
        Although, ChatGPT gave the proper answer, it can’t have been done with this pure brute force program. It takes for ever, even for one PIN.

        Like

      • Jim Randell's avatar

        Jim Randell 3:48 pm on 3 February 2026 Permalink | Reply

        This code looks like it might solve the puzzle, although it has decided to generate all possible sequences of 7 numbers and the check to see if it can find any that work (which itself quite a slow approach). But the code it has written for doing this is terrible.

        First it selects 4 digits from 10 (= C(10, 4) = 210 arrangements, and also means it is assuming that all the digits are different), then for each of these it considers all possible permutations of the digits (= P(4, 4) = 24 arrangements), discarding those that begin with a zero. It then makes a sorted list of all arrangements of these digits that do not have a leading zero (up to P(4, 4) = 24 arrangements), and then considers all possible 7 digit permutations of this list (not combinations so they are already correctly sorted), which accounts for up to 1,744,364,160 checks for each of the possible 210 × 24 = 5,040 sequences of digits. So in total it is trying about 8.7 × 10^12 possible sequences, including many repeated checks.

        It is no wonder it does not run in a reasonable time. For quite a straightforward problem ChatGPT has made a real mess of it.

        As Samuel Johnson might say, “[it] is like a dog walking on his hind legs. It is not done well; but you are surprised to find it done at all”.

        In my experience ChatGPT is good at producing something that looks plausible. So you need to know enough about what you are asking it, so that you can determine if the answer is actually reasonable. And this case, it is a massive failure.

        The really scary thing is that some people treat its responses as though they are correct.

        Liked by 1 person

    • Ruud's avatar

      Ruud 7:06 am on 2 February 2026 Permalink | Reply

      I asked ChatGPT again (mentioning that it didn’t finish in reosonable time). And now it comes with a solution. Amazing …

      from collections import defaultdict
      
      SWAP_PAIRS = [(0,1), (0,2), (0,3), (1,2), (1,3), (2,3)]
      
      def swap_digits(s, i, j):
          if i == j:
              return s
          lst = list(s)
          lst[i], lst[j] = lst[j], lst[i]
          return "".join(lst)
      
      def build_neighbors():
          """
          neighbors[n] = sorted list of all valid 4-digit numbers obtainable by swapping two digits of n
                         (leading digit cannot become 0).
          """
          neighbors = [[] for _ in range(10000)]
          for n in range(1000, 10000):
              s = f"{n:04d}"
              seen = set()
              for i, j in SWAP_PAIRS:
                  t = swap_digits(s, i, j)
                  if t[0] == "0":
                      continue
                  m = int(t)
                  if m != n and m not in seen:
                      seen.add(m)
              neighbors[n] = sorted(seen)
          return neighbors
      
      def find_chains():
          neighbors = build_neighbors()
      
          # Precompute which numbers satisfy divisibility by k (k=1..7)
          div_ok = {k: [False]*10000 for k in range(1, 8)}
          for n in range(1000, 10000):
              for k in range(1, 8):
                  div_ok[k][n] = (n % k == 0)
      
          solutions = []
      
          def dfs(chain):
              step = len(chain) + 1  # next step index (1..7)
              if step == 8:
                  solutions.append(chain[:])
                  return
      
              prev = chain[-1]
      
              for nxt in neighbors[prev]:
                  if nxt <= prev:
                      continue
                  if not div_ok[step][nxt]:
                      continue
                  # only the 7th is divisible by 7
                  if step < 7 and nxt % 7 == 0:
                      continue
                  dfs(chain + [nxt])
      
          # Step 1: any 4-digit number works for divisibility by 1,
          # but it must allow an increasing chain of swaps.
          # Still, searching all 9000 starts is fine with pruning.
          for start in range(1000, 10000):
              # (Optional) tiny prune: if start has no larger neighbors, skip
              if not neighbors[start] or neighbors[start][-1] <= start:
                  continue
              dfs([start])
      
          return solutions
      
      if __name__ == "__main__":
          sols = find_chains()
          print(f"Found {len(sols)} solution chain(s).")
          for ch in sols:
              print(" -> ".join(map(str, ch)), " | third PIN:", ch[2])
      

      Like

      • Ruud's avatar

        Ruud 4:26 pm on 3 February 2026 Permalink | Reply

        I fully agree with you. But when told ChatGPT that this code does not run in reasonable time, it immediately came up with a way better solution (see my reply). And I find that amazing.

        Like

    • GeoffR's avatar

      GeoffR 10:09 am on 4 February 2026 Permalink | Reply

      Interesting reply from ChatGPT, after I put to it that it was not very efficient at coding teasers.

      It looks as though the problem is recognised and things may improve in the future. Quite a lot of detailed comments – things can only get better!

      https://chatgpt.com/share/698313ad-02fc-8000-ab4c-2a3873afb266

      Like

  • Unknown's avatar

    Jim Randell 8:33 am on 30 January 2026 Permalink | Reply
    Tags:   

    Teaser 2331: Everyone’s invited 

    From The Sunday Times, 27th May 2007 [link]

    The letters A, B, C, D, E, F, G, H and I stand for the digits 1 to 9 in some order. Thus AB, CD and EF are two-digit numbers; [and] GHI is a three-digit number. George and Martha arranged a big wedding for their granddaughter. The top table consisted of AB members (fewer than 60) of their extended family. There were CD other tables each seating EF guests. The total attendance was GHI (fewer than 500).

    What was the total attendance?

    [teaser2331]

     
    • Jim Randell's avatar

      Jim Randell 8:34 am on 30 January 2026 Permalink | Reply

      Here is a solution using the [[ SubstitutedExpression ]] solver from the enigma.py library.

      It runs in 92ms. (Internal runtime of the generated code is 14.8ms).

      #! python3 -m enigma -rr
      
      SubstitutedExpression
      
      --digits="1-9"
      
      "A < 6"  # or: "AB < 60"
      "G < 5"  # or: "GHI < 500"
      "AB + CD * EF = GHI"
      
      --template="(AB CD EF GHI)"
      --answer="GHI"
      

      Solution: The total attendance was 489.

      The top table seated 57.

      And then there were either 12 additional tables, each seating 36; or 36 additional tables, each seating 12.

      The total attendance is thus: 57 + 12 × 36 = 489.

      Like

    • ruudvanderham's avatar

      ruudvanderham 9:46 am on 30 January 2026 Permalink | Reply

      import peek
      import istr
      
      for A, B, C, D, E, F, G, H, I in istr.permutations(range(1, 10)):
          if A <= 5 and G <= 4 and (A | B) + (C | D) * (E | F) == (G | H | I):
              peek((A | B), (C | D), (E | F), (G | H | I))
      

      Like

    • GeoffR's avatar

      GeoffR 5:52 pm on 30 January 2026 Permalink | Reply

      from itertools import permutations
      dgts = set('123456789')
      
      for p1 in permutations(dgts, 2):
          A, B = p1
          AB = int(A + B)
          if AB < 60:
              q1 = dgts.difference({A, B})
              for p2 in permutations(q1):
                  C, D, E, F, G, H, I = p2
                  CD, EF = int(C + D), int(E + F)
                  GHI = int(G + H + I)
                  if GHI == AB + CD * EF:
                      if GHI < 500:
                          print(f"Total attendance = {GHI}")
      
      # Total attendance = 489
      
      

      Like

    • BRG's avatar

      BRG 9:30 am on 3 February 2026 Permalink | Reply

      # 10.A + B + (10.C + D).(10.E + F) == 100.G + 10.H + I < 500
      # note: the order of C and E is undetermined (use C < E)
      
      from itertools import permutations
      
      # start with C and E: 100.C.E < 500  E < 4 // C + 1
      for C in range(1, 10):
        for E in range(C + 1, 4 // C + 1):
          s8 = set(range(1, 10)) - {C, E}
          # complete the number of tables (CD) and the number on tables (EF)
          for D, F in permutations(s8, 2):
            CD, EF = 10 * C + D, 10 * E + F
            s6 = s8 - {D, F}
            # now find the number on the top table (AB < 60)
            for A, B in permutations(s6, 2):
              if (AB := 10 * A + B) < 60:
                # find the attendance (< 500) and ensure correct digit allocations
                GHI = (AB := 10 * A + B) + CD * EF
                s_ghi = {int(x) for x in str(GHI)}
                if GHI < 500 and len(s_ghi) == 3 and s_ghi.issubset(s6 - {A, B}):
                  print(f"({AB = }) + ({CD = }) x ({EF = }) == ({GHI = })")
      

      Like

  • Unknown's avatar

    Jim Randell 10:05 am on 27 January 2026 Permalink | Reply
    Tags: by: Derek Emley   

    Teaser 2415: [Double shift] 

    From The Sunday Times, 4th January 2009 [link]

    I have written down a large number in which no digit occurs more than twice. If I were to move the last digit of the number from the end to the front of the number, then the effect would be to double the number. If I repeated the process with the new number, then the effect would be to double it again. And if I repeated the process again, the effect would be to double the number yet again.

    What is the number that I have written down?

    This puzzle was originally published with no title.

    [teaser2415]

     
    • Jim Randell's avatar

      Jim Randell 10:06 am on 27 January 2026 Permalink | Reply

      If we suppose the original number n is of the form:

      n = 10a + z
      where z is the final digit, and a is a k-digit number

      Then moving the final digit to the front gives us:

      2n = (10^k)z + a

      From which we derive that a is a k-digit number, such that:

      19a = (10^k − 2)z

      If the number contains no digit more than twice, then the longest the number can be is 20 digits long, and so we can consider k up to 19.

      This Python program runs in 70ms. (Internal runtime is 719µs).

      from enigma import (irange, div, nsplit, rotate, zip_eq, seq2str, printf)
      
      # check a candidate number <n> (with digits <ds>)
      def check(n, ds):
        # check no digit occurs more than twice
        if any(ds.count(x) > 2 for x in set(ds)): return
        # record shifts that result in doublings
        ns = [n]
        # collect doubling sequences
        while True:
          n *= 2
          ds = rotate(ds, -1)
          if not zip_eq(ds, nsplit(n)): break
          ns.append(n)
        return ns
      
      # look for up to 19 digits prefixes
      for k in irange(1, 19):
        x = 10**k - 2
        # consider possible final digits
        for z in irange(1, 9):
          a = div(x * z, 19)
          if a is None: continue
          n = 10*a + z
          ds = nsplit(n)
          if len(ds) != k + 1: continue
          ns = check(n, ds)
          if ns and len(ns) >= 4:
            printf("{ns}", ns=seq2str(ns, sep=" -> ", enc=""))
      

      Solution: The number is: 105263157894736842.

      The number is 18 digits long, and uses each digit twice except 0 and 9 (which are used once each).

      Shifting the final digit to the front multiple times we get:

      105263157894736842 = n
      210526315789473684 = n × 2
      421052631578947368 = n × 4
      842105263157894736 = n × 8

      A run of 4 is the longest run we can get in base 10 (as n × 16 will not have the same number of digits as n), but there is another run of 3 we can make:

      157894736842105263 = n
      315789473684210526 = n × 2
      631578947368421052 = n × 4

      These numbers are the repetends of fractions of the form k / 19.

      Like

    • Frits's avatar

      Frits 8:51 am on 31 January 2026 Permalink | Reply

      '''
        n = xbcd where x is a k-digit number and b,c and d are digits 
      2.n = dxbc
      4.n = cdxb
      8.n = bcdx with x, b and c all even
      
      8.n = bcdx also has k+3 digits so b = 8 and first digit of x = 1
         --> c = 4 (not 9) and last digit of x must be 6
             d = 2 (as 2.n must be 2.....)
             
      n = 1....6842      
      
        n = xbcd = 1000.x + bcd  (x has k digits)
      8.n = bcdx = 10^k . bcd + x
      
      8000.x + 8.bcd = 10^k . bcd + x
      7999.x = 19.421.x = (10^k - 8).842
      19.x = 2.(10^k - 8)
      '''
            
      for k in range(2, 18):  
        x, r = divmod(2 * (10**k - 8), 19)
        if r: continue
        n = str(x) + "842"
        # no digit occurs more than twice
        if all(n.count(str(i)) <= 2 for i in range(10)): 
          print("answer method 1:", n)
        
      # in order for 2 * (10**k - 8) % 19 = 0 we must have
      # 2 * 10**k % 19 = 16 
      # 2 * 10**k = 19.10**(k - 1) + 10**(k - 1)
      # so 10**(k - 1) % 19 = 16
      
      # 10**(k - 1) % 19 follows a logical pattern
      k = 2
      a = 10**(k - 1) % 19
      while a != 16: 
        a = (a + 19 * (a % 2)) // 2
        k += 1
      
      n = str(2 * (10**k - 8) // 19) + "842"
      # no digit occurs more than twice
      if all(n.count(str(i)) <= 2 for i in range(10)): 
        print("answer method 2:", n)
      

      Like

  • Unknown's avatar

    Jim Randell 8:11 am on 25 January 2026 Permalink | Reply
    Tags:   

    Teaser 3305: Things with scales and things to scale with 

    From The Sunday Times, 25th January 2026 [link] [link]

    Rummaging through a cupboard I came across an old Snakes and Ladders set. The ladders (label them A to E) went from square 4 to 26, 18 to 28, 19 to 73, 22 to 60, and 41 to 98. The snakes (label them W to Z) went from square 53 to 24, 58 to 5, 72 to 33, and 90 to 66. For old times’ sake I couldn’t resist playing a game on my own. Starting from square 1, rolling the die and moving appropriately, travelling travelling up ladders and down snakes when I chanced to land on their starting squares, I happened to finish exactly on square 100. The total of all the numbers I had thrown on the die was 51.

    What was the order of all my up and down jumps? (e.g. A, Y, D).

    [teaser3305]

     
    • Jim Randell's avatar

      Jim Randell 8:56 am on 25 January 2026 Permalink | Reply

      Here is a program that attempts to constructively play games that finish exactly on square 100 and hve a throw total of 51.

      We assume that once a possible game is found, all other possible games have the same sequence of jumps. (I’m thinking about better ways to show the answer to the puzzle is unique).

      It runs in 77ms. (Internal runtime is 1.1ms).

      from enigma import (tuples, seq2str, printf)
      
      # snakes and ladders
      jumps = {
        # ladders (lower -> higher)
        (4, 26): 'A', (18, 28): 'B', (19, 73): 'C', (22, 60): 'D', (41, 98): 'E',
        # snakes (higher -> lower)
        (53, 24): 'W', (58, 5): 'X', (72, 33): 'Y', (90, 66): 'Z',
      }
      
      # linked squares
      link = dict(jumps.keys())
      
      # possible throws
      throws = [6, 5, 4, 3, 2, 1]
      
      # play the game
      # p = current position
      # t = target position
      # b = throw budget (must not be exceeded)
      # ds = dice throws
      # ps = positions
      def play(p, t, b, ds=[], ps=[]):
        ps = ps + [p]
        # are we done
        if p == t or p >= 100 or b <= 0:
          yield (ds, ps, b)
        elif b > 0:
          # make the next roll
          for d in throws:
            if not (d > b):
              # move the player
              p1 = p + d
              # perform any jump
              p2 = link.get(p1)
              # continue play
              if p2 is None:
                yield from play(p1, t, b - d, ds + [d], ps)
              else:
                yield from play(p2, t, b - d, ds + [d], ps + [p1])
      
      # find a possible game
      for (ds, ps, r) in play(1, 100, 51):
        if r == 0 and ps[-1] == 100:
          printf("throws = {ds} (sum = {t}) -> positions = {ps}", t=sum(ds))
          # find the jumps involved
          js = tuple(filter(None, (jumps.get(k) for k in tuples(ps, 2))))
          printf("jumps = {js}", js=seq2str(js, enc="[]"))
          break
      

      Solution: The jumps made are: C, Z, Y, E.

      So the game proceeds as follows:

      dice throws of 18: move 1 → 19 (avoiding 4, 18)
      take ladder C from 19 → 73
      dice throws of 17: move 73 → 90
      take snake Z from 90 → 66
      dice throws of 6: move 66 → 72
      take snake Y from 72 → 33
      dice throws of 8: move 33 → 41
      take ladder E from 41 → 98
      dice throws of 2: move 98 → 100
      total dice throws = 18 + 17 + 6 + 8 + 2 = 51

      Like

      • Jim Randell's avatar

        Jim Randell 1:28 pm on 25 January 2026 Permalink | Reply

        Here is a better solution. It is shorter, faster, can be used to experiment with different throw budgets, and it finds all solutions (thereby showing the answer to the original puzzle is unique).

        We don’t care about the actual dice throws, a game is made up of a sequence of contiguous blocks (that are moved with throws of the dice) with jumps (i.e. a snake or a ladder) between the blocks. The blocks themselves can usually be made by lots of dice throws (and the starts of the jumps are sufficiently fragmented that we can always avoid any unwanted jumps).

        This Python program makes a collection of possible contiguous segments, and then joins a sequence of them together with jumps inbetween to make a game that starts at 1, ends at 100, and requires a total of 51 to be scored on the dice throws during the segments.

        It runs in 71ms. (Internal runtime is 88µs).

        from enigma import (defaultdict, tuples, seq2str, printf)
        
        # snakes and ladders
        jumps = {
          # ladders (lower -> higher)
          (4, 26): 'A', (18, 28): 'B', (19, 73): 'C', (22, 60): 'D', (41, 98): 'E',
          # snakes (higher -> lower)
          (53, 24): 'W', (58, 5): 'X', (72, 33): 'Y', (90, 66): 'Z',
        }
        
        # linked squares
        link = dict(jumps.keys())
        
        # possible contiguous segments; segs: start -> ends
        segs = defaultdict(list)
        seg = lambda x, y: segs[x].append(y)
        seg(1, 100)  # no jumps
        for (a, b) in jumps.keys():
          # add in 1 to the start of a jump
          seg(1, a)
          # add in end of a jump to 100
          seg(b, 100)
          # add in end of a jump to start of a jump
          for (x, y) in jumps.keys():
            if b < x: seg(b, x)
        
        # find contiguous segments from <s> to <t> with throw budget <b>
        def solve(s, t, b, ss=[]):
          # are we done?
          if s == t and b == 0:
            yield ss
          elif s < 100 and b > 0:
            # add in the next segment
            for x in segs[s]:
              d = x - s
              if not (d > b):
                yield from solve(link.get(x, x), t, b - d, ss + [(s, x)])
        
        # find games from 1 to 100 with a throw budget of B
        B = 51
        for ss in solve(1, 100, B):
          # find jumps used
          js = tuple(jumps[(b, x)] for ((a, b), (x, y)) in tuples(ss, 2))
          printf("{B}: {ss} -> {js}", js=seq2str(js, enc="[]"))
        

        Liked by 1 person

  • Unknown's avatar

    Jim Randell 9:48 am on 23 January 2026 Permalink | Reply
    Tags:   

    Teaser 2462: [What NOW?] 

    From The Sunday Times, 29th November 2009 [link]

    Puzzlers are often confused about whether the number 1 is prime or square, so perhaps this Teaser will clarify the issue!

    • ONE is not prime, but it is an odd perfect square;
    TWO is divisible by 2 but not 4;
    • The number of odd primes less than SIX is TWO.

    In those statements digits have consistently been replaced by capital letters, with different letters being used for different digits.

    What is the number NOW?

    This puzzle was originally published with no title.

    [teaser2462]

     
    • Jim Randell's avatar

      Jim Randell 9:49 am on 23 January 2026 Permalink | Reply

      Here is a solution using the [[ SubstitutedExpression ]] solver from the enigma.py library.

      The following run-file executes in 98ms. (Internal runtime of the generated code is 14.4ms).

      #! python3 -m enigma -rr
      
      SubstitutedExpression
      
      # no leading zeros (ONE, TWO, SIX, NOW)
      --invalid="0,OTSN"
      
      # collect primes < 1000
      --code="primes.expand(999)"
      
      # ONE is not prime, but it is an odd perfect square
      "ONE not in primes"
      "E % 2 = 1"
      "is_square(ONE)"
      
      # TWO is divisible by 2, but not 4
      "O % 2 = 0"
      "WO % 4 != 0"
      
      # the number of odd primes less than SIX is TWO
      "icount(primes.between(3, SIX - 1)) = TWO"
      
      --template="(ONE) (TWO) (SIX)"
      --answer="NOW"
      

      Solution: NOW = 820.

      There are two possible assignments of digits to letters:

      ONE = 289, TWO = 102, SIX = 564
      ONE = 289, TWO = 102, SIX = 567

      The next prime after 563 is 569, so we count 102 odd primes if X is 4 or 7.

      Like

      • Frits's avatar

        Frits 9:09 am on 24 January 2026 Permalink | Reply

        @Jim, your code allows N to be zero. Is this what you wanted?

        Like

    • ruudvanderham's avatar

      ruudvanderham 11:24 am on 23 January 2026 Permalink | Reply

      import peek
      import istr
      
      for o, n, e, t, w, s, i, x in istr.permutations(range(10), 8):
          if o * t * s != 0:
              if not (one := istr("=one")).is_prime() and one.is_odd() and one.is_square():
                  if (two := istr("=two")).is_divisible_by(2) and not two.is_divisible_by(4):
                      if len(istr.primes(3, (six := istr("=six")))) == two:
                          peek(one, two, six)
      

      Like

  • Unknown's avatar

    Jim Randell 9:16 am on 20 January 2026 Permalink | Reply
    Tags:   

    Teaser 2363: [A round number] 

    From The Sunday Times, 6th January 2008 [link]

    We are used to thinking of 1,000 as a “round number”, but this is very much based on 10. One definition of a round number is that it should have lots of small factors, and certainly that it should be divisible by every number up to and including sixteen. There is one such round number that, when written in a certain base (of less than 10,000), looks like 1111. What is more, its base can be found very neatly.

    What is that base?

    This puzzle was originally published with no title.

    [teaser2363]

     
    • Jim Randell's avatar

      Jim Randell 9:17 am on 20 January 2026 Permalink | Reply

      Programatically, it is straightforward to just try all possible bases.

      This Python program runs in 75ms. (Internal runtime is 4.2ms).

      from enigma import (irange, mlcm, call, nconcat, printf)
      
      # M = LCM(2..16)
      M = call(mlcm, irange(2, 16))
      
      # consider possible bases
      for b in irange(2, 9999):
        # n = 1111 [base b]
        n = nconcat([1, 1, 1, 1], base=b)
        # check for divisibility by 2..16
        if n % M == 0:
          # output solution
          printf("base={b} n={n}")
      

      But here is a more sophisticated approach:

      Another way to write 1111 [base b] is: b^3 + b^2 + b + 1, which is an integer valued polynomial function.

      And this means we can use the [[ poly_roots_mod() ]] solver from the enigma.py library (described here: [ link ]) to solve the puzzle.

      The following Python program has an internal runtime of 572µs.

      from enigma import (Polynomial, rev, irange, mlcm, call, poly_roots_mod, printf)
      
      # calculate 1111 [base b]
      p = Polynomial(rev([1, 1, 1, 1]))
      
      # M = LCM(2..16)
      M = call(mlcm, irange(2, 16))
      
      # find roots of p(b) = 0 [mod M] that give a valid base
      roots = poly_roots_mod(p, 0)
      for b in roots(M):
        if 1 < b < 10000:
          # calculate the corresponding n value
          n = p(b)
          # output solution
          printf("base={b} n={n}")
      

      Solution: The base is 5543.

      And the round number is: 1111 [base 5543] = 170338568400 [decimal] = 720720 × 236345.

      Like

    • Ruud's avatar

      Ruud 10:52 am on 20 January 2026 Permalink | Reply

      import istr
      
      print(*(base for base in istr.range(2, 10000) if all(sum(base**i for i in range(4)).is_divisible_by(i) for i in range(2, 17))))
      

      Like

    • Frits's avatar

      Frits 8:33 am on 21 January 2026 Permalink | Reply

      # 1111 [base b] is: b^3 + b^2 + b + 1 or (b + 1)(b^2 + 1)
      # I am not good at modular arithmetic but b^2 + 1 is never a multiple of
      # numbers 4.k + 3. So b + 1 must be divisible by 3, 7 and 11 and thus by 231.
      
      for b1 in range(231, 10001, 231):
        # calculate n = 1111 [base b]
        b = b1 - 1
        n = b1 * (b**2 + 1)
        # n must be divisible by numbers 2-16
        if any(n % i for i in [9, 11, 13, 14, 15, 16]): continue
        print("answer:", b)
      

      Like

      • Jim Randell's avatar

        Jim Randell 9:11 am on 21 January 2026 Permalink | Reply

        @Frits: A neat bit of analysis. That is probably the kind of approach the setter had in mind.

        In fact as (b^2 + 1) is not divisible by 3, then it is also not divisible by 9, so we can proceed in steps of: 9 × 7 × 11 = 693, which only needs 14 iterations.

        This Python program has an internal runtime of 34µs:

        from enigma import (irange, printf)
        
        S = 9 * 7 * 11
        R = 720720 // S
        for i in irange(S, 10000, step=S):
          b = i - 1
          n = i * (b*b + 1)
          if n % R == 0:
            printf("base={b} n={n}")
        

        Like

        • Jim Randell's avatar

          Jim Randell 9:40 am on 21 January 2026 Permalink | Reply

          In fact although (b^2 + 1) may be divisible by 2, it cannot be divisible by 4, so we can move in steps of:

          S = 8 × 9 × 7 × 11 = 5544

          And, as the base is limited to be less than 10000, there is only one value to check (or if we accept that there is a solution to the puzzle, then there are no values to check).

          Like

          • Frits's avatar

            Frits 1:10 pm on 21 January 2026 Permalink | Reply

            @Jim, good work.

            if b is even then b=2k and b^2 + 1 = 4k^2 + 1
            if b is odd then b = 2k+1 and b^2 + 1 = 4k^2 + 4k + 2

            so indeed b^2 + 1 cannot be divisible by 4.

            Like

  • Unknown's avatar

    Jim Randell 6:38 am on 18 January 2026 Permalink | Reply
    Tags:   

    Teaser 3304: Roaming bull 

    From The Sunday Times, 18th January 2026 [link] [link]

    Farmer Quentin keeps his prize bull in a circular field of diameter 50m. To improve the layout, he decides to switch to a square field with side length equal to the old diameter. He builds the new fencing around the old, with fence posts every metre starting at the corner. After completing the new fencing, he tethers the bull outside the fence to one of these fence posts with a rope of integer metre length, to allow the removal of the inner circular fence. As a result, the bull’s temporary roaming area is now four times what it was inside the circle.

    What is the length of the rope?

    [teaser3304]

     
    • Jim Randell's avatar

      Jim Randell 7:14 am on 18 January 2026 Permalink | Reply

      If the bull were tethered to a single post with a 50 m rope in an otherwise unobstructed flat plain, then it would be able to roam a region that is 4 times the area of the original (25 m radius) circular field. So the rope must be at least this long.

      When tethered to a post that makes up the boundary of the square field, then bull can roam over a collection of quadrants of a circle are centred on the tether point, and the corners of the square field, as the rope wraps around the boundary of the field.

      I considered rope lengths allowing roaming areas of between 2 and 6 non-overlapping quadrants (of various sizes) around the outside of the field. (Which assumes the bull has no other obstructions). If the rope is longer than 100 m then the regions will overlap, as the bull can reach the opposite point on the perimeter of the square from either direction.

      For each possible tethering point a corresponding equation is generated and then solved to find possible integer rope lengths.

      The following Python code runs in 79ms. (Internal runtime is 2.1ms).

      from enigma import (Rational, Polynomial as Poly, irange, sq, divc, sprintf as f, printf)
      
      Q = Rational()
      q = Q(1, 4)
      
      d = 50  # size of the square
      A = sq(d)  # target area (= 4 * r^2 where r = d/2)
      
      # find roots of polynomial <p> = <v> between <lo> and <hi>
      def roots(p, v, lo, hi, s=''):
        xs = p.roots(v, domain='Z', include='+', F=Q)  # integer roots
        for x in xs:
          if lo <= x <= hi:
            printf("{s}x={x}")
      
      # suppose the bull is tethered at post a = 0 (corner) to 25 (middle)
      # with a rope of length x
      for a in irange(0, divc(d, 2)):
      
        # 2 quadrants: 0 <= x <= a
        p = 2*q * sq(Poly([0, 1]))  # x^2
        roots(p, A, 0, a, f("[2 quads] a={a} -> "))
      
        # 3 quadrants: a <= x <= d - a
        p += q * sq(Poly([-a, 1]))  # (x - a)^2
        roots(p, A, a, d - a, f("[3 quads] a={a} -> "))
      
        # 4 quadrants: d - a <= x <= d + a
        p += q * sq(Poly([a - d, 1]))  # (x + (a - d))^2
        roots(p, A, d - a, d + a, f("[4 quads] a={a} -> "))
      
        # 5 quadrants: d + a <= x <= 2d - a
        p += q * sq(Poly([-(a + d), 1]))  # (x - (a + d))^2
        roots(p, A, d + a, 2*d - a, f("[5 quads] a={a} -> "))
      
        # 6 quadrants (no overlap): 2d - a <= x <= 2d
        p += q * sq(Poly([a - 2*d, 1]))  # (x + (a - 2d))^2
        roots(p, A, 2*d - a, 2*d, f("[6 quads] a={a} -> "))
      

      Solution: The length of the rope is 58 m.

      And the tether is at post 2 m from a corner.

      The bull can roam in two quadrants with radius 58 m, one quadrant with radius 56 m, one quadrant with radius 10 m, and one quadrant with radius 6 m.

      Here is a diagram of the situation – the light green area (outside the square field) is 4 times the size of the dark green area (inside the square field):


      If Farmer Quentin only measures the rope to approximately a whole number of metres, then there are two more solutions where the rope is within 4 cm of a whole number of metres:

      rope = 58.99 m; tether = 6 m from a corner
      rope = 60.03 m; tether = 12 m from a corner

      We can see these non-integer solutions by setting [[ domain='F', F='float' ]] at line 11 in the program above.

      Like

      • Jim Randell's avatar

        Jim Randell 11:00 am on 18 January 2026 Permalink | Reply

        Alternatively, just considering all possible rope lengths and tether points (although this doesn’t let you find non-integer rope lengths).

        This Python program runs in 392µs.

        from enigma import (irange, sq, divc, printf)
        
        d = 50  # size of the square
        A = 4 * sq(d)  # target area (in quarter units)
        
        # consider possible tether points
        for a in irange(0, divc(d, 2)):
        
          # consider increasing rope length
          for x in irange(d, 2*d):
        
            # calculate total area of possible quadrants
            rs = [x, x, x - a, x + a - d, x - a - d, x + a - 2*d]
            v = sum(sq(r) for r in rs if r > 0)
        
            # output solution
            if v == A: printf("a={a} x={x} [quads={q}]", q=sum(r > 0 for r in rs))
            if v >= A: break
        

        Like

    • Frits's avatar

      Frits 1:43 pm on 18 January 2026 Permalink | Reply

      3 areas (or 4 quadrants) will definitely be roamed as I don’t let the rope length start from 1.
      A 6th quadrant is not possible for diameter 50 as I have calculated a basic upper limit for the rope length.

      d = 50 # diameter in meters
      
      # old roaming area = 25^2.pi so new roaming area must be 50^2.pi
      # southern area S = r^2 / 2 < 2500, r^2 < 5000
      mx_rope = int((2 * d**2)**.5)
      
      # the rope length must be larger than the diameter
      for r in range(d + 1, mx_rope + 1):
        # tether the bull to the southern fence (on the west side)
        
        for y in range(26):   # distance from SW corner
          # quadruple areas divided by pi
          S4 = 2 * r**2        # 4 x area below the southern fence
          NW4 = (r - y)**2 
          N4 = (r - d - y)**2 if r - d - y > 0 else 0
          E4 = (r - d + y)**2 
          
          # all areas should sum to 100^2
          if S4 + NW4 + N4 + E4 == 4 * d**2:
            print("answer:", r, "meters")
      

      Like

  • Unknown's avatar

    Jim Randell 8:11 am on 16 January 2026 Permalink | Reply
    Tags: ,   

    Teaser 2312: Backward step 

    From The Sunday Times, 14th January 2007 [link]

    Seb had just been given his four-digit PIN, and he was afraid that he would not be able to remember it. So he broke all the rules and wrote it in his pocket diary. But to make it “more secure” he did not actually write the PIN; instead, he wrote the digits in reverse order. He was surprised to discover that the new number was a multiple of the correct PIN.

    What is his PIN?

    Note that without additional requirements there are many solutions to this puzzle. The intended solution seems to come from the requirement that all the digits of the PIN are non-zero.

    [teaser2312]

     
    • Jim Randell's avatar

      Jim Randell 8:12 am on 16 January 2026 Permalink | Reply

      Here is a solution using the [[ SubstitutedExpression ]] solver from the enigma.py library.

      It runs in 82ms. (Internal runtime of the generated code is 1.7ms).

      #! python3 -m enigma -rr
      
      SubstitutedExpression
      
      # suppose the real PIN is ABCD
      "ediv(DCBA, ABCD) > 1"
      "D >= A" # [optional]
      
      --distinct=""
      --invalid=""
      --digits="1-9"
      --answer="ABCD"
      

      Solution: The PIN is: 2178.

      And so the reversed PIN is: 8712.

      And: 8712 = 4 × 2178.

      (The multiple solutions to the puzzle as published can be seen by removing the digit restriction on line 11).


      Without the restriction to non-zero digits there are 131 solutions, for example (reversed-PIN, PIN):

      1000 & 0001
      1010 & 0101

      9801 & 1089

      9990 & 0999

      (Although not all these would be surprising).

      But only one of these solutions remains if the digits of the PIN must all be non-zero.


      The published solution was: “1089 or 2178”.

      Like

    • Ruud's avatar

      Ruud 10:33 am on 16 January 2026 Permalink | Reply

      import istr
      print(*(pin for digits in istr.product(range(1, 10), repeat=4) if (pin:=istr.join(digits))[::-1].divided_by(pin) not in (1, None)))
      

      Like

    • GeoffR's avatar

      GeoffR 7:43 pm on 16 January 2026 Permalink | Reply

      from enigma import nsplit, is_pairwise_distinct
      
      for pin in range(1234, 9876):
          a, b, c, d = nsplit(pin)
          if 0 in (a, b, c, d): continue
          if is_pairwise_distinct(a, b, c, d):
              rev_pin = 1000*d + 100*c + 10*b + a
              q, r = divmod(rev_pin, pin)
              if r == 0 and q > 1:
                 print(f"Pin = {pin}.")
      
      
      

      Like

  • Unknown's avatar

    Jim Randell 3:34 pm on 14 January 2026 Permalink | Reply
    Tags:   

    Brain teaser 983: Superchamp 

    From The Sunday Times, 24th May 1981 [link]

    The five champion athletes competed against one another in their five special events to decide who was the supreme champion (the one with the highest number of points). Three points were awarded for the winner in each event. two points for second place, and one for third.

    The Superchamp won more events than anyone else. All scored a different number of points, and all scored in a different number of events.

    Ben and Colin together scored twice as many points as Fred. Eddie was the only one to win his own special event, and in it the Superchamp came second. In another event Eddie gained one point less than the hurdler. The hurdler only came third in the hurdles, which was won by Denis, who was last in the long jump but scored in the sprint.
    Fred won the long jump and was second in the walk, but came nowhere in the hurdles.

    Ben scored in the long jump and Colin scored in the sprint. The thousand-metre man was third in two events. The long jumper scored more points than the sprinter.

    Who was the [long] jumper, and what was his score?

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

    [teaser983]

     
    • Jim Randell's avatar

      Jim Randell 3:35 pm on 14 January 2026 Permalink | Reply

      There are a lot of conditions to this puzzle, so I used the minizinc.py library to allow me to construct a declarative model for it in MiniZinc, which is then solved, and the Python program used to format the solutions.

      It runs in 545ms.

      from enigma import (require, printf)
      from minizinc import MiniZinc
      
      require("sys.version", "3.6") # needed to support [ use_embed=1 ]
      
      # indices for names and events (1..5)
      (B, C, D, E, F) = (1, 2, 3, 4, 5)
      (hurdles, long_jump, sprint, m1000, walk) = (1, 2, 3, 4, 5)
      
      # construct the MiniZinc model
      m = MiniZinc([
        'include "globals.mzn"',
      
        # scores for the competitors in each event: pts[event, competitor] = score
        "array [1..5, 1..5] of var 0..3: pts",
      
        # scores in each event are: 3, 2, 1, 0, 0
        "constraint forall (i in 1..5) (sum (j in 1..5) (pts[i, j] = 3) = 1)", # 1st = 3pts
        "constraint forall (i in 1..5) (sum (j in 1..5) (pts[i, j] = 2) = 1)", # 2nd = 2pts
        "constraint forall (i in 1..5) (sum (j in 1..5) (pts[i, j] = 1) = 1)", # 3rd = 1pts
        "constraint forall (i in 1..5) (sum (j in 1..5) (pts[i, j] = 0) = 2)", # unplaced = 0pts
      
        # functions:
        "function var int: points(var int: j) = sum (i in 1..5) (pts[i, j])",
        "function var int: wins(var int: j) = sum (i in 1..5) (pts[i, j] = 3)",
        "function var int: scored(var int: j) = sum (i in 1..5) (pts[i, j] > 0)",
      
        # "the superchamp scored more points than anyone else"
        "var 1..5: S",
        "constraint forall (j in 1..5 where j != S) (points(j) < points(S))",
      
        # "the superchamp won more events than anyone else"
        "constraint forall (j in 1..5 where j != S) (wins(j) < wins(S))",
      
        # each competitor scored a different number of points
        "constraint all_different (j in 1..5) (points(j))",
      
        # each competitor scored in a different number of events
        "constraint all_different (j in 1..5) (scored(j))",
      
        # "B and C together scored twice as many points as F"
        "constraint points({B}) + points({C}) = 2 * points({F})",
      
        # "E was the only one to win his own event"
        # "and in that event the superchamp came second"
        "array [1..5] of var 1..5: spe",
        "constraint all_different(spe)",
        "constraint forall (j in 1..5) ((j == {E}) <-> (pts[spe[j], j] = 3))",
        "constraint pts[spe[{E}], S] = 2",
      
        # "in another event E gained 1 point less than the hurdler"
        "var 1..5: hurdler",
        "constraint spe[hurdler] = {hurdles}",
        "constraint exists (i in 1..5) (pts[i, {E}] + 1 = pts[i, hurdler])",
      
        # "the hurdler only came third in hurdles"
        "constraint pts[{hurdles}, hurdler] = 1",
      
        # "hurdles was won by D"
        "constraint pts[{hurdles}, {D}] = 3",
      
        # "D came last in long jump"
        "constraint pts[{long_jump}, {D}] = 0",
      
        # "D scored in the sprint"
        "constraint pts[{sprint}, {D}] > 0",
      
        # "F won the long jump"
        "constraint pts[{long_jump}, {F}] = 3",
      
        # "F was 2nd in the walk"
        "constraint pts[{walk}, {F}] = 2",
      
        # "F did not score in hurdles"
        "constraint pts[{hurdles}, {F}] = 0",
      
        # "B scored in the long jump"
        "constraint pts[{long_jump}, {B}] > 0",
      
        # "C scored in the sprint"
        "constraint pts[{sprint}, {C}] > 0",
      
        # "the 1000m man was 3rd in 2 events"
        "var 1..5: m1000er",
        "constraint spe[m1000er] = {m1000}",
        "constraint sum (i in 1..5) (pts[i, m1000er] = 1) = 2",
      
        # "the long jumper scored more points than the sprinter"
        "var 1..5: long_jumper",
        "constraint spe[long_jumper] = {long_jump}",
        "var 1..5: sprinter",
        "constraint spe[sprinter] = {sprint}",
        "constraint points(long_jumper) > points(sprinter)",
      
      ], use_embed=1)
      
      
      # map indices back to names / events (for output)
      name = {1: "Ben", 2: "Colin", 3: "Denis", 4: "Eddie", 5: "Fred"}
      event = {1: "hurdles", 2: "long jump", 3: "sprint", 4: "1000m", 5: "walk"}
      
      # solve the model and find:
      # pts = results in each event
      # spe = special event for each competitor
      for (pts, spe) in m.solve(solver="minizinc -a", result="pts spe"):
        # collect points
        t = dict((k, 0) for k in name.keys())
      
        # output the results for each event
        for (i, rs) in enumerate(pts, start=1):
          (p1, p2, p3) = (rs.index(p) + 1 for p in (3, 2, 1))
          printf("{e}: 1st = {p1}, 2nd = {p2}, 3rd = {p3}", e=event[i], p1=name[p1], p2=name[p2], p3=name[p3])
          # collect points
          t[p1] += 3
          t[p2] += 2
          t[p3] += 1
        printf()
      
        # determine superchamp
        S = max(t.keys(), key=t.get)
        assert all(k == S or v < t[S] for (k, v) in t.items())
      
        # output the results for each competitor
        for j in sorted(event.keys()):
          printf("{j} [{e}]: {t} points{S}", j=name[j], e=event[spe[j - 1]], t=t[j], S=(' [SUPERCHAMP]' if j == S else ''))
        printf("--")
        printf()
      

      Solution: Denis is the long jumper. He scored 5 points.

      The program finds 2 possible scenarios:

      hurdles: 1st = Denis, 2nd = Eddie, 3rd = Ben
      long jump: 1st = Fred, 2nd = Ben, 3rd = Eddie
      sprint: 1st = Ben, 2nd = Denis, 3rd = Colin
      1000m: 1st = Eddie, 2nd = Ben, 3rd = Fred
      walk: 1st = Ben, 2nd = Fred, 3rd = Eddie

      Ben [hurdles]: 11 points [SUPERCHAMP]
      Colin [sprint]: 1 points
      Denis [long jump]: 5 points
      Eddie [1000m]: 7 points
      Fred [walk]: 6 points

      hurdles: 1st = Denis, 2nd = Eddie, 3rd = Colin
      long jump: 1st = Fred, 2nd = Ben, 3rd = Colin
      sprint: 1st = Colin, 2nd = Denis, 3rd = Eddie
      1000m: 1st = Eddie, 2nd = Colin, 3rd = Fred
      walk: 1st = Colin, 2nd = Fred, 3rd = Eddie

      Ben [sprint]: 2 points
      Colin [hurdles]: 10 points [SUPERCHAMP]
      Denis [long jump]: 5 points
      Eddie [1000m]: 7 points
      Fred [walk]: 6 points

      The solution published in the book (which runs to 3 pages) only gives the first of these solutions.

      I think this is due to the interpretation of “In another event Eddie gained one point less than the hurdler”. The book solution seems to infer (hurdler = 3pts, Eddie = 2pts) or (hurdler = 2pts, Eddie = 1pt), and concludes it is not possible for C to be the champ.

      And in the first scenario, in the long jump, we have: the hurdler (Ben) scores 2pts (2nd place), and Eddie scores 1pt (3rd place).

      However, I think the wording also allows (hurdler = 1pt, Eddie = 0pts), and in the second scenario, in the long jump, we have: the hurdler (Colin) scores 1pt (3rd place), and Eddie scores 0pts (unplaced).

      Like

    • Frits's avatar

      Frits 3:06 pm on 17 January 2026 Permalink | Reply

      from itertools import permutations
      
      '''        3   2   1       
      hurdles    A   F   K        
      long J     B   G   L        
      sprint     C   H   M              super=Superchamp
      1000m      D   I   N        
      Walk       E   J   O        
      '''
      
      sports = [-1, -1, -1, -1, -1]
      (ben, colin, denis, eddie, fred) = range(5)
      
      dgts, sols = set(range(5)), set()
      
      A = denis # Denis won hurdles
      B = fred  # Fred won the long jump
      J = fred  # Fred was 2nd in the walk
      
      # Fred came nowhere in the hurdles
      for F, K in permutations(dgts - {A, fred}, 2):    # hurdles
        # hurdler (K) came 3rd in the hurdles, Eddie is no hurdler
        if eddie == K: continue
        for G, L in permutations(dgts - {B, denis}, 2): # Denis last in long jump
          if 0 not in {G, L} : continue                 # Ben scored in long jump
          for C, H, M in permutations(dgts, 3):         # sprint
            # Colin and Denis scored in the sprint
            if not {C, H, M}.issuperset({colin, denis}): continue 
            for D, I, N in permutations(dgts, 3):       # 1000m
              for E, O in permutations(dgts - {J}, 2):  # walk
                gold   = [A, B, C, D, E]
                silver = [F, G, H, I, J]
                bronze = [K, L, M, N, O]
                # Eddie was the only one to win his own special event
                if eddie not in gold: continue
                scores = [A, F, K, B, G, L, C, H, M, D, I, N, E, J, O]
                scored = [scores.count(i) for i in range(5)]
                # all scored in a different number of events.
                if len(set(scored)) != 5: continue
                
                pts = [sum([3 - (i % 3) for i, s in enumerate(scores) if s == j]) 
                       for j in range(5)]
                # all scored a different number of points
                if len(set(pts)) != 5: continue
                # Ben and Colin together scored twice as many points as Fred
                if pts[ben] + pts[colin] != 2 * pts[fred]: continue
                # the Superchamp won more events than anyone else ( >= 2)
                sups = sorted((f, i) for i in range(5) if (f := gold.count(i)) > 1)
                if not sups or (len(sups) == 2 and len(set(gold)) == 3): continue
                
                super = sups[-1][1]
                # once the Superchamp came 2nd after Eddie
                if super == eddie or super not in silver: continue
                # the Superchamp had the highest number of points
                if pts[super] != max(pts): continue
                
                sports[0] = K  # hurdler only came third in the hurdles
                      
                # check sports where Eddie and Superchamp ended 1 and 2
                for e, (g, s) in enumerate(zip(gold, silver)):
                  if (g, s) != (eddie, super): continue
                  
                  if e == 0: continue # Eddie is not the hurdler
                  # in another event Eddie gained one point less than the hurdler
                  for i, gsb in enumerate(zip(gold, silver, bronze)):
                    if ((K, eddie) in zip(gsb, gsb[1:]) or 
                        (eddie not in gsb and gsb[-1] == K)): break
                  else: # no break
                    break    
                  
                  sports_ = sports.copy()
                  sports_[e] = eddie  # Eddie performs sport <e>
                  # assign people to remaining sports
                  for p in permutations(dgts - {eddie, K}):
                    sports__ = sports_.copy()
                    j = 0
                    for i in range(5):
                      if sports_[i] != -1: continue
                      sports__[i] = p[j]
                      j += 1
                    
                    # Eddie was the only one to win his own special event
                    for i, s in enumerate(sports__):
                      if gold[i] == s and s != eddie: break
                    else: # no break  
                      # the long jumper scored more points than the sprinter
                      if not (pts[sports__[1]] > pts[sports__[2]]): continue
                      # the thousand-metre man was third in two events
                      if bronze.count(sports__[3]) != 2: continue
                      # store solution
                      sols.add((sports__[1], pts[sports__[1]]))
      
      names = "Ben Colin Denis Eddie Fred".split()                
      print("answer:", ' or '.join(names[a] + ' with score ' + str(s) 
                                    for a, s in sols))         
      

      Like

  • Unknown's avatar

    Jim Randell 6:25 am on 11 January 2026 Permalink | Reply
    Tags:   

    Teaser 3303: Knights and knaves 

    From The Sunday Times, 11th January 2026 [link] [link]

    On my travels, I came across a group of some knights (always truthful) and some knaves (always lying). At first, I couldn’t tell which were knights and which were knaves. However, six individuals then gave the following statements about their group:

    “The number of knights is prime.”
    “The number of knights is odd.”
    “The number of knaves is square.”
    “The number of knaves is even.”
    “The total of knights and knaves is an odd number.”
    “There are more knaves than knights.”

    These statements enabled me to deduce the composition of the group.

    How many (a) knights and (b) knaves were in the group?

    [teaser3303]

     
    • Jim Randell's avatar

      Jim Randell 6:47 am on 11 January 2026 Permalink | Reply

      The setter has an additional piece of information – i.e. they can observe the total number of people in the group. If it is possible to break this total down in into knights and knaves in only one way that is consistent with the statements made, then the composition of the group can be determined with certainty.

      The following Python program runs in 71ms. (Internal runtime is 158µs).

      from enigma import (irange, inf, decompose, filter2, is_prime, is_square_p, printf)
      
      # consider increasing group sizes (at least 6)
      for t in irange(6, inf):
        # collect candidate solutions for this total size
        sols = list()
        # decompose into (a) knights and (b) knaves
        for (a, b) in decompose(t, 2, min_v=1, increasing=0, sep=0):
      
          # evaluate the statements
          ss = filter2(bool, [
            # 1. "a is prime"
            is_prime(a),
            # 2. "a is odd"
            (a % 2 == 1),
            # 3. "b is square"
            is_square_p(b),
            # 4. "b is even"
            (b % 2 == 0),
            # 5. "a + b is odd"
            (t % 2 == 1),
            # 6. "b > a"
            (b > a),
          ])
      
          # check minimum group sizes
          if len(ss.true) > a or len(ss.false) > b: continue
          # record this candidate
          sols.append((a, b))
      
        printf("[{t} -> {sols}]")
        # check for unique solutions
        if len(sols) == 1:
          (a, b) = sols[0]
          printf("a = {a}; b = {b}")
          break
      

      Solution: (a) There are 5 knights; (b) There are are 2 knaves.

      The total size of the group is 7, and the statements made are:

      1. True (“the number of knights is prime” = 7)
      2. True (“the number of knights is odd” = 5)
      3. False (“the number of knaves is square” = 2)
      4. True (“the number of knaves is even” = 2)
      5. True (“the total number of knights and knaves is odd” = 7)
      6. False (“there are more knaves than knights” 5 > 2)

      There are 4 true statements, and 2 false statements, so both knaves made a false statement, and 4 of the 5 knights made a true statement.

      And this is the only way a group of 7 can be broken down consistent with the statements.

      If we allow the program to continue to larger group sizes, we see that the number of candidate breakdowns grows, so it would not be possible to determine the composition of a larger group.

      Like

  • Unknown's avatar

    Jim Randell 9:58 pm on 9 January 2026 Permalink | Reply
    Tags:   

    Teaser 2360: [Flower arranging] 

    From The Sunday Times, 16th December 2007 [link]

    In the following statements and instruction, digits have been consistently replaced by letters, with different letters for different digits.

    F + L + O + W + E + R raised to the power P is equal to the six-digit number FLOWER.

    FACTOR is divisible by A, R and T.

    What is the value of FLOWER ART?

    This puzzle was originally published with no title.

    [teaser2360]

     
    • Jim Randell's avatar

      Jim Randell 10:03 pm on 9 January 2026 Permalink | Reply

      Here is a solution using the [[ SubstitutedExpression ]] solver from the enigma.py library.

      It runs in 226ms. (Internal runtime of the generated code is 126ms).

      #! python3 -m enigma -rr
      
      SubstitutedExpression
      
      "pow(F + L + O + W + E + R, P) = FLOWER"
      
      "FACTOR % A = 0"
      "FACTOR % R = 0"
      "FACTOR % T = 0"
      
      --answer="(FLOWER, ART)"
      

      Solution: FLOWER ART = 390625 751.

      And:

      FLOWER = 390625 = 25^4 = (3 + 9 + 0 + 6 + 2 + 5) ^ 4.
      FACTOR = 378105 is divisible by 7, 5, 1.

      Like

    • Ruud's avatar

      Ruud 6:11 am on 10 January 2026 Permalink | Reply

      import istr
      
      for f, l, o, w, e, r, p in istr.permutations(range(10), 7):
          if sum(istr("=flower")) ** p == istr("=flower"):
              for a, c, t in istr.permutations(range(10), 3):
                  if istr("=flowerpact").all_distinct() and all(istr("=factor").is_divisible_by(x) for x in (a, r, t)):
                      print(istr("=flower"), istr("=art"))
      

      Like

      • ruudvanderham's avatar

        ruudvanderham 11:32 am on 10 January 2026 Permalink | Reply

        This version is *much* faster. Note that it required the latest version of istr (1.1.16):

        import istr
        
        for p in range(2, 10):
            for flower in istr.power_ofs(p, 100000, 1000000):
                if sum(flower) ** p == flower:
                    istr.decompose(flower, "flower")
                    for a, c, t in istr.permutations(set(istr.range(10))-set(flower)-{p}, 3):
                        if istr("=flowerpact").all_distinct() and all(istr("=factor").is_divisible_by(x) for x in (a, r, t)):
                            print(istr("=flower"), istr("=art"))
        

        Like

    • GeoffR's avatar

      GeoffR 2:48 pm on 10 January 2026 Permalink | Reply

      Note: P = 5 is max value for int_pow() can accomodate without an error, but OK for a solution.

      % A Solution in MiniZinc
      include "globals.mzn";
      
      var 1..9:F; var 1..9:A; var 1..9:R; var 2..5:P;  
      var 0..9:L; var 0..9:O; var 0..9:W; var 0..9:E;
      var 1..9:T; var 0..9:C;
      
      constraint all_different ([F, A, R, P, L, O, W, E, T, C]);
      
      var 100000..999999:FLOWER == 100000*F + 10000*L + 1000*O
      + 100*W + 10*E + R;
      
      var 100000..999999:FACTOR = 100000*F + 10000*A + 1000*C
      + 100*T + 10*O + R;
      
      var 100..999:ART = 100*A + 10*R + T;
      
      var 2..54:SUM = F + L + O + W + E + R;
      
      constraint int_pow(SUM, P, FLOWER);
      
      constraint FACTOR mod A == 0 /\ FACTOR mod R == 0 /\ FACTOR mod T == 0;
      
      solve satisfy;
      output["FLOWER = " ++ show(FLOWER) ++ ", ART = " ++ show(ART)];
      
      % FLOWER = 390625, ART = 751
      % ----------
      % ==========
      
      
      

      Like

    • Brian Gladman's avatar

      Brian Gladman 7:40 pm on 10 January 2026 Permalink | Reply

      from itertools import permutations
      
      # convert digits to numbers and vice versa
      dgts_to_nbr = lambda dgts: int(''.join(map(str, dgts)))
      nbr_to_dgts = lambda nbr: tuple(int(d) for d in str(nbr))
      
      # the digit sum of FLOWER is between the minimum 
      # and maximum sums of six digits from 0..9
      for sm in range(15, 40):
        # the possible powers to give sm ** P six digits
        for P in (4, 5):
          if 100_000 <= (FLOWER := sm ** P) < 1_000_000:
            t = (F, L, O, W, E, R) = nbr_to_dgts(FLOWER)
            # check that three digits remain unallocated
            if len(r3 := set(range(10)).difference(t + (P,))) == 3:
              # consider the order of the remaining digits for A, C and T
              for A, C, T in permutations(r3):
                FACTOR = dgts_to_nbr((F, A, C, T, O, R))
                # FACTOR must be divisible by A, R and T
                if FACTOR % (A * R * T) == 0:
                  ART = dgts_to_nbr((A, R, T))
                  print(f"FLOWER ART = {FLOWER} {ART} [{FACTOR = }, {P = }]")
      

      Like

  • Unknown's avatar

    Jim Randell 11:02 am on 6 January 2026 Permalink | Reply
    Tags:   

    Brain teaser 981: Bailing out 

    From The Sunday Times, 10th May 1981 [link]

    The pirate ship “Nancy” had one leaky hold. As long as the water was not allowed to rise above a certain level there was no danger of the ship sinking; so the practice was to allow the water to rise to a mark on the side of the hold which was just below the danger level, and then to send in a team of about 15 or 20 pirates to bale out the hold until it was empty. The water came in continuously at a constant: rate, so the process had, to be repeated regularly.

    There were two kinds of baling equipment: practical pans and capacious cans (which emptied the water at different rates), and each pirate who was assigned to baling duty picked up whichever of these was nearest to hand.

    One baling party consisting of 11 pirates with practical pans and 6 pirates with capacious cans emptied the hold in 56 minutes. When the water had risen again, the next party of 5 pirates with practical pans and 12 with capacious cans emptied it in 35 minutes. A third party of 15 with practical pans plus 4 with capacious cans took exactly an hour to do the job.

    How long would it take a party of 6 with practical pans and 10 with capacious cans?

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

    [teaser981]

     
    • Jim Randell's avatar

      Jim Randell 11:02 am on 6 January 2026 Permalink | Reply

      If we treat the volume of water at the point that baling starts as 1 unit, then we can write the following equation for a team with P pans and C cups as:

      T(P.p + C.c + f) = 1

      P.p + C.c + f = 1/T

      where:

      T is the total time taken to empty the hold (min);
      p is the rate at which a pan removes water (units/min);
      c is the rate at which a cup removes water (units/min);
      f is the rate at which the hold fills (units/min) (this will be negative as water is flowing into the hold).

      For the three teams given we get the following equations:

      11p + 6c + f = 1/56
      5p + 12c + f = 1/35
      15p + 4c + f = 1/60

      This gives us three equations in three variables, which can be solved to give the rates p, c and f.

      We can then calculate the time taken for the 4th team:

      T(6p + 10c + f) = 1

      T = 1/(6p + 10c + f)

      The following Python program runs in 74ms. (Internal runtime is 186µs).

      from enigma import (Matrix, Rational, printf)
      
      Q = Rational()
      
      # construct the equations
      eqs = [
        #  p   c   f   1/time
        ((11,  6,  1), Q(1, 56)), # team 1 (11p + 6c) takes 56 minutes
        (( 5, 12,  1), Q(1, 35)), # team 2 (5p + 12c) takes 35 minutes
        ((15,  4,  1), Q(1, 60)), # team 3 (15p + 4c) takes 60 minutes
      ]
      
      (p, c, f) = Matrix.linear(eqs, field=Q)
      printf("[p={p} c={c} f={f}]")
      
      # calculate time for team 4 (6p + 10c)
      t = Q(1, 6*p + 10*c + f)
      printf("team 4 takes {t} minutes")
      

      Solution: It would take the 4th team 42 minutes to empty the hold.

      We get:

      p = 1/840
      c = 1/336
      f = −11/840

      1/T = 6/840 + 10/336 − 11/840
      1/T = 1/42
      T = 42

      So the water is coming in at 11/840 units/min, and a pirate with a pail can empty out 1/840 units/min. So 11 pirates with pails would be able to remove the water at the rate it was coming in. A pirate with a cup can empty 1/336 units/min (so a cup can bail more than a pail), and 2.5 pirates with cups could remove water at the rate it is coming in.

      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