Skip to content

Sunday Times Teaser 3213 – A Streetcar Named Divisor

by BRG on April 19, 2024

by Colin Vout

Published Friday April 19 2024 (link)

In retrospect it was inadvisable to ask an overenthusiastic mathematician to overhaul our local tram routes. They allocated a positive whole number less than 50 to each district’s tram stop. To find the number of the tram going from one district to another you would “simply” (their word, not mine) find the largest prime divisor of the difference between the two districts’ numbers; if this was at least 5 it was the unique route number, and if not there was no direct route.

The routes, each in increasing order of the stop numbers, were: Atworth, Bratton, Codford; Atworth, Downlands, Enford; Bratton, Figheldean, Enford; Downlands, Figheldean, Codford; Codford, Enford.

What were the route numbers, in the order quoted above?

From → Uncategorized

8 Comments Leave one →
  1. BRG permalink

    Painfully slow in CPython but tolerable using PyPy (but now amended with speed improvements suggested by Frits).

    • John Z permalink

      or:

    • John Z permalink

      Could line 45 use permutations instead of combinations and remove line 46?

      • BRG permalink

        Yes but it would be slower since, for the majority of the inputs, there will be
        many more permutations than there are twice the number of combinations.

        • JohnZ permalink

          Permutations gives n.(n-1) iterations. Combinations followed by two
          way flip gives n.(n-1)/2 . 2: the same. I put in a count += 1 in the
          loop. Curiously at the point where a solution is found, there are
          14255 iterations with combinations (should be even but isn’t!) but
          14250 iterations with permutations. At the end of the run they have
          both done 86744 iterations. The difference in the count when the
          solution is found leaves me perplexed.

          • BRG permalink

            HI John, You are right about this. The original line 45
            combined three items (a, b, d) which made the approach
            faster. But when I later removed the ‘a’ (by setting it
            to 1) the approach no longer offered a speed advantage.

            I think the odd count simply means that the solution
            is output on the first time the inner loop runs, not
            the second.

  2. JohnZ permalink

    Great solution Brian. I permit myself some “kibbitzing”:

    A few lines could be saved (but no speed gain) by removing line 7 and replacing lines 10 – 15 with:

    • BRG permalink

      A nice suggestion, John. I often overlook the set like features of dictionaries
      since they are a relatively recent addition to Python.

Leave a Reply

Note: HTML is allowed. Your email address will not be published.

Subscribe to this comment feed via RSS