<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="../feed.xsl" type="text/xsl"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Susam's Puzzles</title>
  <subtitle>Feed for Susam's Puzzles</subtitle>
  <link href="https://susam.net/"/>
  <link href="https://susam.net/tag/puzzle.xml" rel="self"/>
  <id>https://susam.net/tag/puzzle.xml</id>
  <updated>2025-12-06T00:00:00Z</updated>
  <author><name>Susam Pal</name></author>
  <entry>
    <title>Fizz Buzz in CSS</title>
    <link href="https://susam.net/fizz-buzz-in-css.html"/>
    <id>urn:uuid:e380ad23-cfde-4836-b214-0e64baf6be65</id>
    <updated>2025-12-06T00:00:00Z</updated>
    <content type="html">
<!-- BEGIN HTML -->
&lt;p&gt;
  How many CSS selectors and declarations do we need to produce the
  Fizz Buzz sequence?  Of course we could do this with no CSS at all
  simply by placing the entire sequence as text in the HTML body.  So
  to make the problem precise as well as to keep it interesting, we
  require that all text that appears in the Fizz Buzz sequence comes
  directly from the CSS.  Placing any part of the output numbers or
  words outside the stylesheet is not allowed.  JavaScript is not
  allowed either.  With these constraints, I think we need at least
  four CSS selectors along with four declarations to solve this
  puzzle, as shown below:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;li { counter-increment: n }
li:not(:nth-child(5n))::before { content: counter(n) }
li:nth-child(3n)::before { content: &quot;Fizz&quot; }
li:nth-child(5n)::after { content: &quot;Buzz&quot; }&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  Here is a complete working example:
  &lt;a href=&quot;css-fizz-buzz.html&quot;&gt;css-fizz-buzz.html&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
  The above solution contains four CSS rules with one selector and one
  declaration in each rule.  For example,
  &lt;code&gt;li { counter-increment: n }&lt;/code&gt; is one rule consisting of
  the selector &lt;code&gt;li&lt;/code&gt; and the declaration
  &lt;code&gt;counter-increment: n&lt;/code&gt;.
&lt;/p&gt;
&lt;p&gt;
  Seasoned code golfers looking for a challenge can probably shrink
  this solution further.  A common trick to solve this problem is to
  use an ordered list (&lt;code&gt;&amp;lt;ol&amp;gt;&lt;/code&gt;) which provides the
  integers in the form of list markers automatically, thereby
  eliminating the need to maintain a counter in the stylesheet.
  However, this violates the requirement set out in the introduction.
  We want every integer to be produced directly by the stylesheet.
  Treating the integers in the list markers as part of the output
  sequence breaks this rule.  Not to mention the output looks untidy
  because of the unnecessary dot after each marker and also because
  the numbers and words appear misaligned.  See an example of that
  trick here:
  &lt;a href=&quot;code/web/css-fizz-buzz-ol.html&quot;&gt;css-fizz-buzz-ol.html&lt;/a&gt;.
  Correcting the misaligned output calls for extra code that cancels
  out the number of declarations saved.  In any case, the requirement
  that all integers of the output must come directly from the
  stylesheet prevents untidy solutions like this and also forces us to
  rely on the capabilities of CSS to solve this puzzle.
&lt;/p&gt;
&lt;p&gt;
  The intention here was to obtain the smallest possible code in terms
  of the number of CSS declarations.  This example is not crafted to
  minimise bytes, but for code golfers who enjoy reducing byte count,
  here is the number of bytes this solution consumes after removing
  all whitespace:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ curl -sS https://susam.net/css-fizz-buzz.html | sed -n &apos;/counter/,/after/p&apos; | tr -d &apos;[:space:]&apos; | wc -c
152&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  Further reduction in byte count can be achieved by using the
  &lt;code&gt;&amp;lt;p&amp;gt;&lt;/code&gt; element instead of &lt;code&gt;&amp;lt;li&amp;gt;&lt;/code&gt;,
  nesting CSS selectors, etc.  I&apos;ll leave that as an exercise for the
  reader.  Returning to the focus of this post as well as to summarise
  it, the solution here uses four CSS rules consisting of four
  selectors and four declarations to render the Fizz Buzz sequence.
&lt;/p&gt;
<!-- ### -->
&lt;p&gt;
  &lt;a href="https://susam.net/fizz-buzz-in-css.html"&gt;Read on website&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/absurd.html&quot;&gt;#absurd&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/web.html&quot;&gt;#web&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/technology.html&quot;&gt;#technology&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/css.html&quot;&gt;#css&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/puzzle.html&quot;&gt;#puzzle&lt;/a&gt;
&lt;/p&gt;
<!-- END HTML -->
    </content>
  </entry>
  <entry>
    <title>Fizz Buzz with Cosines</title>
    <link href="https://susam.net/fizz-buzz-with-cosines.html"/>
    <id>urn:uuid:91190abf-f9ce-4d98-82b9-7fabd6bbdb14</id>
    <updated>2025-11-20T00:00:00Z</updated>
    <content type="html">
<!-- BEGIN HTML -->
&lt;p&gt;
  Fizz Buzz is a counting game that has become oddly popular in the
  world of computer programming as a simple test of basic programming
  skills.  The rules of the game are straightforward.  Players say the
  numbers aloud in order beginning with one.  Whenever a number is
  divisible by 3, they say &apos;Fizz&apos; instead.  If it is divisible by 5,
  they say &apos;Buzz&apos;.  If it is divisible by both 3 and 5, the player
  says both &apos;Fizz&apos; and &apos;Buzz&apos;.  Here is a typical Python program that
  prints this sequence:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;for n in range(1, 101):
    if n % 15 == 0:
        print(&apos;FizzBuzz&apos;)
    elif n % 3 == 0:
        print(&apos;Fizz&apos;)
    elif n % 5 == 0:
        print(&apos;Buzz&apos;)
    else:
        print(n)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  Here is the output:
  &lt;a href=&quot;files/blog/fizz-buzz.txt&quot;&gt;fizz-buzz.txt&lt;/a&gt;.  Can we make
  the program more complicated?  The words &apos;Fizz&apos;, &apos;Buzz&apos; and
  &apos;FizzBuzz&apos; repeat in a periodic manner throughout the sequence.
  What else is periodic?  Trigonometric functions!  Perhaps we can use
  trigonometric functions to encode all four rules of the sequence in
  a single closed-form expression.  That is what we are going to
  explore in this article, for fun and no profit.
&lt;/p&gt;
&lt;p&gt;
  By the end, we will obtain a discrete Fourier series that can take
  any integer \( n \) and select the corresponding text to be printed.
  In fact, we will derive it using two different methods.  First, we
  will follow a long-winded but hopefully enjoyable approach that
  relies on a basic understanding of complex exponentiation, geometric
  series and trigonometric functions.  Then, we will obtain the same
  result through a direct application of the discrete Fourier
  transform.
&lt;/p&gt;
&lt;h2 id=&quot;contents&quot;&gt;Contents&lt;/h2&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;#definitions&quot;&gt;Definitions&lt;/a&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#symbol-functions&quot;&gt;Symbol Functions&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#index-function&quot;&gt;Index Function&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#fizz-buzz-sequence&quot;&gt;Fizz Buzz Sequence&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#from-indicator-functions-to-cosines&quot;&gt;From Indicator Functions to Cosines&lt;/a&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#indicator-functions&quot;&gt;Indicator Functions&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#complex-exponentials&quot;&gt;Complex Exponentials&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#cosines&quot;&gt;Cosines&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#dft&quot;&gt;Discrete Fourier Transform&lt;/a&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#one-period-of-fizz-buzz&quot;&gt;One Period of Fizz Buzz&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#fourier-coefficients&quot;&gt;Fourier Coefficients&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#inverse-transform&quot;&gt;Inverse Transform&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#conclusion&quot;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;definitions&quot;&gt;Definitions&lt;/h2&gt;
&lt;p&gt;
  Before going any further, we establish a precise mathematical
  definition for the Fizz Buzz sequence.  We begin by introducing a
  few functions that will help us define the Fizz Buzz sequence later.
&lt;/p&gt;
&lt;h3 id=&quot;symbol-functions&quot;&gt;Symbol Functions&lt;/h3&gt;
&lt;p&gt;
  We define a set of four functions \( \{ s_0, s_1, s_2, s_3 \} \) for
  integers \( n \) by:

  \begin{align*}
    s_0(n) &amp;amp;= n, \\
    s_1(n) &amp;amp;= \mathtt{Fizz}, \\
    s_2(n) &amp;amp;= \mathtt{Buzz}, \\
    s_3(n) &amp;amp;= \mathtt{FizzBuzz}.
  \end{align*}

  We call these the symbol functions because they produce every term
  that appears in the Fizz Buzz sequence.  The symbol function \( s_0
  \) returns \( n \) itself.  The functions \( s_1, \) \( s_2 \) and
  \( s_3 \) are constant functions that always return the literal
  words \( \mathtt{Fizz}, \) \( \mathtt{Buzz} \) and \(
  \mathtt{FizzBuzz} \) respectively, no matter what the value of \( n
  \) is.
&lt;/p&gt;
&lt;h3 id=&quot;index-function&quot;&gt;Index Function&lt;/h3&gt;
&lt;p&gt;
  We define a function \( f(n) \) for integer \( n \) by

  \[
    f(n) = \begin{cases}
      1 &amp;amp; \text{if } 3 \mid n \text{ and } 5 \nmid n, \\
      2 &amp;amp; \text{if } 3 \nmid n \text{ and } 5 \mid n, \\
      3 &amp;amp; \text{if } 3 \mid n \text{ and } 5 \mid n, \\
      0 &amp;amp; \text{otherwise}.
    \end{cases}
  \]

  The notation \( m \mid n \) means that the integer \( m \) divides
  the integer \( n, \) i.e. \( n \) is a multiple of \( m.  \)
  Equivalently, there exists an integer \( c \) such that \( n = cm
 .  \)  Similarly, \( m \nmid n \) means that \( m \) does not divide
  \( n, \) i.e. \( n \) is not a multiple of \( m.  \)
&lt;/p&gt;
&lt;p&gt;
  This function covers all four conditions involved in choosing the \(
  n \)th item of the Fizz Buzz sequence.  As we will soon see, this
  function tells us which of the four symbol functions produces the \(
  n \)th item of the Fizz Buzz sequence.  For this reason, we call \(
  f(n) \) the index function.
&lt;/p&gt;
&lt;h3 id=&quot;fizz-buzz-sequence&quot;&gt;Fizz Buzz Sequence&lt;/h3&gt;
&lt;p&gt;
  We now define the Fizz Buzz sequence as the sequence

  \[
    (s_{f(n)}(n))_{n = 1}^{\infty}
  \]

  We can expand the first few terms of the sequence explicitly as
  follows:

  \begin{align*}
    (s_{f(n)}(n))_{n = 1}^{\infty}
    &amp;amp;= (s_{f(1)}(1), \; s_{f(2)}(2), \; s_{f(3)}(3), \; s_{f(4)}(4), \;
            s_{f(5)}(5), \; s_{f(6)}(6), \; s_{f(7)}(7), \; \dots) \\
    &amp;amp;= (s_0(1), \; s_0(2), \; s_1(3), \; s_0(4),
            s_2(5), \; s_1(6), \; s_0(7), \; \dots) \\
    &amp;amp;= (1, \; 2, \; \mathtt{Fizz}, \; 4, \;
            \mathtt{Buzz}, \; \mathtt{Fizz}, \; 7, \; \dots).
  \end{align*}

  Note how the function \( f(n) \) produces an index \( i \) which we
  then use to select the symbol function \( s_i(n) \) to produce the
  \( n \)th term of the sequence.  This is precisely why we decided to
  call \( f(n) \) the index function while defining it in the previous
  section.
&lt;/p&gt;
&lt;h2 id=&quot;from-indicator-functions-to-cosines&quot;&gt;From Indicator Functions to Cosines&lt;/h2&gt;
&lt;p&gt;
  Here we discuss the first method of deriving our closed form
  expression, starting with indicator functions and rewriting them
  using complex exponentials and cosines.
&lt;/p&gt;
&lt;h3 id=&quot;indicator-functions&quot;&gt;Indicator Functions&lt;/h3&gt;
&lt;p&gt;
  Here is the index function \( f(n) \) from the previous section with
  its cases and conditions rearranged to make it easier to spot
  interesting patterns:

  \[
    f(n) = \begin{cases}
      0 &amp;amp; \text{if } 5 \nmid n \text{ and } 3 \nmid n, \\
      1 &amp;amp; \text{if } 5 \nmid n \text{ and } 3 \mid n, \\
      2 &amp;amp; \text{if } 5 \mid n \text{ and } 3 \nmid n, \\
      3 &amp;amp; \text{if } 5 \mid n \text{ and } 3 \mid n.
    \end{cases}
  \]

  This function helps us select another function \( s_{f(n)}(n) \)
  which in turn determines the \( n \)th term of the Fizz Buzz
  sequence.  Our goal now is to replace this piecewise formula with a
  single closed-form expression.  To do so, we first define indicator
  functions \( I_m(n) \) as follows:

  \[
    I_m(n) = \begin{cases}
      1 &amp;amp; \text{if } m \mid n, \\
      0 &amp;amp; \text{if } m \nmid n.
    \end{cases}
  \]

  The formula for \( f(n) \) can now be written as:

  \[
    f(n) = \begin{cases}
      0 &amp;amp; \text{if } I_5(n) = 0 \text{ and } I_3(n) = 0, \\
      1 &amp;amp; \text{if } I_5(n) = 0 \text{ and } I_3(n) = 1, \\
      2 &amp;amp; \text{if } I_5(n) = 1 \text{ and } I_3(n) = 0, \\
      3 &amp;amp; \text{if } I_5(n) = 1 \text{ and } I_3(n) = 1.
    \end{cases}
  \]

  Do you see a pattern?  Here is the same function written as a table:
&lt;/p&gt;
&lt;table class=&quot;grid center textcenter&quot;&gt;
  &lt;tr&gt;
    &lt;th&gt;\( I_5(n) \)&lt;/th&gt;
    &lt;th&gt;\( I_3(n) \)&lt;/th&gt;
    &lt;th&gt;\( f(n) \)&lt;/th&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;\( 0 \)&lt;/td&gt;
    &lt;td&gt;\( 0 \)&lt;/td&gt;
    &lt;td&gt;\( 0 \)&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;\( 0 \)&lt;/td&gt;
    &lt;td&gt;\( 1 \)&lt;/td&gt;
    &lt;td&gt;\( 1 \)&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;\( 1 \)&lt;/td&gt;
    &lt;td&gt;\( 0 \)&lt;/td&gt;
    &lt;td&gt;\( 2 \)&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;\( 1 \)&lt;/td&gt;
    &lt;td&gt;\( 1 \)&lt;/td&gt;
    &lt;td&gt;\( 3 \)&lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;
&lt;p&gt;
  Do you see it now?  If we treat the values in the first two columns
  as binary digits and the values in the third column as decimal
  numbers, then in each row the first two columns give the binary
  representation of the number in the third column.  For example, \(
  3_{10} = 11_2 \) and indeed in the last row of the table, we see the
  bits \( 1 \) and \( 1 \) in the first two columns and the number \(
  3 \) in the last column.  In other words, writing the binary digits
  \( I_5(n) \) and \( I_3(n) \) side by side gives us the binary
  representation of \( f(n).  \)  Therefore

  \[
    f(n) = 2 \, I_5(n) + I_3(n).
  \]

  We can now write a small program to demonstrate this formula:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;for n in range(1, 101):
    s = [n, &apos;Fizz&apos;, &apos;Buzz&apos;, &apos;FizzBuzz&apos;]
    i = (n % 3 == 0) + 2 * (n % 5 == 0)
    print(s[i])&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  We can make it even shorter at the cost of some clarity:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;for n in range(1, 101):
    print([n, &apos;Fizz&apos;, &apos;Buzz&apos;, &apos;FizzBuzz&apos;][(n % 3 == 0) + 2 * (n % 5 == 0)])&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  What we have obtained so far is pretty good.  While there is no
  universal definition of a closed-form expression, I think most
  people would agree that the indicator functions as defined above are
  simple enough to be permitted in a closed-form expression.
&lt;/p&gt;
&lt;h3 id=&quot;complex-exponentials&quot;&gt;Complex Exponentials&lt;/h3&gt;
&lt;p&gt;
  In the previous section, we obtained the formula

  \[
    f(n) = I_3(n) + 2 \, I_5(n)
  \]

  which we then used as an index to look up the text to be printed.
  We also argued that this is a pretty good closed-form expression
  already.
&lt;/p&gt;
&lt;p&gt;
  However, in the interest of making things more complicated, we must
  ask ourselves: What if we are not allowed to use the indicator
  functions?  What if we must adhere to the commonly accepted meaning
  of a closed-form expression which allows only finite combinations of
  basic operations such as addition, subtraction, multiplication,
  division, integer exponents and roots with integer index as well as
  functions such as exponentials, logarithms and trigonometric
  functions.  It turns out that the above formula can be rewritten
  using only addition, multiplication, division and the cosine
  function.  Let us begin the translation.  Consider the sum

  \[
    S_m(n) = \sum_{k = 0}^{m - 1} e^{i 2 \pi k n / m},
  \]

  where \( i \) is the imaginary unit and \( n \) and \( m \) are
  integers.  This is a geometric series in the complex plane with
  ratio \( r = e^{i 2 \pi n / m}.  \)  If \( n \) is a multiple of \( m
 , \) then \( n = cm \) for some integer \( c \) and we get

  \[
    r
    = e^{i 2 \pi n / m}
    = e^{i 2 \pi c}
    = 1.
  \]

  Therefore, when \( n \) is a multiple of \( m, \) we get

  \[
    S_m(n)
    = \sum_{k = 0}^{m - 1} e^{i 2 \pi k n / m}
    = \sum_{k = 0}^{m - 1} 1^k
    = m.
  \]

  If \( n \) is not a multiple of \( m, \) then \( r \ne 1 \) and the
  geometric series becomes

  \[
    S_m(n)
    = \frac{r^m - 1}{r - 1}
    = \frac{e^{i 2 \pi n} - 1}{e^{i 2 \pi n / m} - 1}
    = 0.
  \]

  Therefore,

  \[
    S_m(n) = \begin{cases}
      m &amp;amp; \text{if } m \mid n, \\
      0 &amp;amp; \text{if } m \nmid n.
    \end{cases}
  \]

  Dividing both sides by \( m, \) we get

  \[
    \frac{S_m(n)}{m} = \begin{cases}
      1 &amp;amp; \text{if } m \mid n, \\
      0 &amp;amp; \text{if } m \nmid n.
    \end{cases}
  \]

  But the right-hand side is \( I_m(n).  \)  Therefore

  \[
    I_m(n)
    = \frac{S_m(n)}{m}
    = \frac{1}{m} \sum_{k = 0}^{m - 1} e^{i 2 \pi k n / m}.
  \]
&lt;/p&gt;
&lt;h3 id=&quot;cosines&quot;&gt;Cosines&lt;/h3&gt;
&lt;p&gt;
  We begin with Euler&apos;s formula

  \[
    e^{i x} = \cos x + i \sin x
  \]

  where \( x \) is a real number.  From this formula, we get

  \[
    e^{i x} + e^{-i x} = 2 \cos x.
  \]

  Therefore

  \begin{align*}
    I_3(n)
    &amp;amp;= \frac{1}{3} \sum_{k = 0}^2 e^{i 2 \pi k n / 3} \\
    &amp;amp;= \frac{1}{3} \left( 1 + e^{i 2 \pi n / 3} +
                                  e^{i 4 \pi n / 3} \right) \\
    &amp;amp;= \frac{1}{3} \left( 1 + e^{i 2 \pi n / 3} +
                                  e^{-i 2 \pi n / 3} \right) \\
    &amp;amp;= \frac{1}{3} + \frac{2}{3} \cos \left( \frac{2 \pi n}{3} \right).
  \end{align*}

  The third equality above follows from the fact that \( e^{i 4 \pi n
  / 3} = e^{i 6 \pi n / 3} e^{-i 2 \pi n / 3} = e^{i 2 \pi n} e^{-i 2
  \pi n/3} = e^{-i 2 \pi n / 3} \) when \( n \) is an integer.
&lt;/p&gt;
&lt;p&gt;
  The function above is defined for integer values of \( n \) but we
  can extend its formula to real \( x \) and plot it to observe its
  shape between integers.  As expected, the function takes the value
  \( 1 \) whenever \( x \) is an integer multiple of \( 3 \) and \( 0
  \) whenever \( x \) is an integer not divisible by \( 3.  \)
&lt;/p&gt;
&lt;figure class=&quot;soft&quot;&gt;
  &lt;img src=&quot;files/blog/fizz-buzz-i3.png&quot; alt=&quot;Graph&quot;&gt;
  &lt;figcaption&gt;
    Graph of \( \frac{1}{3} + \frac{2}{3} \cos \left( \frac{2 \pi x}{3} \right) \)
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  Similarly,

  \begin{align*}
    I_5(n)
    &amp;amp;= \frac{1}{5} \sum_{k = 0}^4 e^{i 2 \pi k n / 5} \\
    &amp;amp;= \frac{1}{5} \left( 1 + e^{i 2 \pi n / 5}
                                + e^{i 4 \pi n / 5}
                                + e^{i 6 \pi n / 5}
                                + e^{i 8 \pi n / 5} \right) \\
    &amp;amp;= \frac{1}{5} \left( 1 + e^{i 2 \pi n / 5}
                                + e^{i 4 \pi n / 5}
                                + e^{-i 4 \pi n / 5}
                                + e^{-i 2 \pi n / 5} \right) \\
    &amp;amp;= \frac{1}{5} + \frac{2}{5} \cos \left( \frac{2 \pi n}{5} \right)
                       + \frac{2}{5} \cos \left( \frac{4 \pi n}{5} \right).
  \end{align*}

  Extending this expression to real values of \( x \) allows us to
  plot its shape as well.  Once again, the function takes the value \(
  1 \) at integer multiples of \( 5 \) and \( 0 \) at integers not
  divisible by \( 5.  \)
&lt;/p&gt;
&lt;figure class=&quot;soft&quot;&gt;
  &lt;img src=&quot;files/blog/fizz-buzz-i5.png&quot; alt=&quot;Graph&quot;&gt;
  &lt;figcaption&gt;
    Graph of \(
      \frac{1}{5}
      + \frac{2}{5} \cos \left( \frac{2 \pi x}{5} \right)
      + \frac{2}{5} \cos \left( \frac{4 \pi x}{5} \right)
    \)
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  Recall that we expressed \( f(n) \) as

  \[
    f(n) = I_3(n) + 2 \, I_5(n).
  \]

  Substituting these trigonometric expressions yields

  \[
    f(n)
    = \frac{1}{3}
      + \frac{2}{3} \cos \left( \frac{2 \pi n}{3} \right)
      + 2 \cdot \left(
        \frac{1}{5}
        + \frac{2}{5} \cos \left( \frac{2 \pi n}{5} \right)
        + \frac{2}{5} \cos \left( \frac{4 \pi n}{5} \right)
      \right).
  \]

  A straightforward simplification gives

  \[
    f(n)
    = \frac{11}{15}
      + \frac{2}{3} \cos \left( \frac{2 \pi n}{3} \right)
      + \frac{4}{5} \cos \left( \frac{2 \pi n}{5} \right)
      + \frac{4}{5} \cos \left( \frac{4 \pi n}{5} \right).
  \]

  We can extend this expression to real \( x \) and plot it as well.
  The resulting curve takes the values \( 0, 1, 2 \) and \( 3 \) at
  integer points, as desired.
&lt;/p&gt;
&lt;figure class=&quot;soft&quot;&gt;
  &lt;img src=&quot;files/blog/fizz-buzz-f.png&quot; alt=&quot;Graph&quot;&gt;
  &lt;figcaption&gt;
    Graph of \(
      \frac{11}{15} +
      \frac{2}{3} \cos \left( \frac{2 \pi x}{3} \right) +
      \frac{4}{5} \cos \left( \frac{2 \pi x}{5} \right) +
      \frac{4}{5} \cos \left( \frac{4 \pi x}{5} \right)
    \)
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  Now we can write our Python program as follows:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;from math import cos, pi
for n in range(1, 101):
    s = [n, &apos;Fizz&apos;, &apos;Buzz&apos;, &apos;FizzBuzz&apos;]
    i = round(11 / 15 + (2 / 3) * cos(2 * pi * n / 3)
                      + (4 / 5) * cos(2 * pi * n / 5)
                      + (4 / 5) * cos(4 * pi * n / 5))
    print(s[i])&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;dft&quot;&gt;Discrete Fourier Transform&lt;/h2&gt;
&lt;p&gt;
  The keen-eyed might notice that the expression we obtained for \(
  f(n) \) is a discrete Fourier series.  This is not surprising, since
  the output of a Fizz Buzz program depends only on \( n \bmod 15.  \)
  Any function on a finite cyclic group can be written exactly as a
  finite Fourier expansion.  In this section, we obtain \( f(n) \)
  using the discrete Fourier transform.  It is worth mentioning that
  the calculations presented here are quite tedious to do by hand.
  Nevertheless, this section offers a glimpse of how such calculations
  are performed.  By the end, we will arrive at exactly the same \(
  f(n) \) as before.  There is nothing new to discover here.  We
  simply obtain the same result by a more direct but more laborious
  method.  If this doesn&apos;t sound interesting, you may safely skip the
  subsections that follow.
&lt;/p&gt;
&lt;h3 id=&quot;one-period-of-fizz-buzz&quot;&gt;One Period of Fizz Buzz&lt;/h3&gt;
&lt;div style=&quot;display: none&quot;&gt;\( \gdef\arraystretch{1.2} \)&lt;/div&gt;
&lt;p&gt;
  We know that \( f(n) \) is a periodic function with period \( 15.  \)
  To apply the discrete Fourier transform, we look at one complete
  period of the function using the values \( n = 0, 1, \dots, 14.  \)
  Over this period, we have:

  \begin{array}{c|ccccccccccccccc}
      n &amp;amp;  0 &amp;amp;  1 &amp;amp;  2 &amp;amp;  3 &amp;amp;  4
        &amp;amp;  5 &amp;amp;  6 &amp;amp;  7 &amp;amp;  8 &amp;amp;  9
        &amp;amp; 10 &amp;amp; 11 &amp;amp; 12 &amp;amp; 13 &amp;amp; 14 \\
    \hline
    f(n) &amp;amp; 3 &amp;amp;  0 &amp;amp;  0 &amp;amp;  1 &amp;amp;  0
         &amp;amp; 2 &amp;amp;  1 &amp;amp;  0 &amp;amp;  0 &amp;amp;  1
         &amp;amp; 2 &amp;amp;  0 &amp;amp;  1 &amp;amp;  0 &amp;amp;  0
  \end{array}

  The discrete Fourier series of \( f(n) \) is

  \[
    f(n) = \sum_{k = 0}^{14} c_k \, e^{i 2 \pi k n / 15}
  \]

  where the Fourier coefficients \( c_k \) are given by the discrete
  Fourier transform

  \[
    c_k = \frac{1}{15} \sum_{n = 0}^{14} f(n) e^{-i 2 \pi k n / 15}.
  \]

  for \( k = 0, 1, \dots, 14.  \)  The formula for \( c_k \) is called
  the discrete Fourier transform (DFT).  The formula for \( f(n) \) is
  called the inverse discrete Fourier transform (IDFT).
&lt;/p&gt;
&lt;h3 id=&quot;fourier-coefficients&quot;&gt;Fourier Coefficients&lt;/h3&gt;
&lt;p&gt;
  Let \( \omega = e^{-i 2 \pi / 15}.  \)  Then using the values of \(
  f(n) \) from the table above, the DFT becomes:

  \[
    c_k = \frac{3 + \omega^{3k} + 2 \omega^{5k} + \omega^{6k}
                  + \omega^{9k} + 2 \omega^{10k} + \omega^{12k}}{15}.
  \]

  Substituting \( k = 0, 1, 2, \dots, 14 \) into the above equation
  gives us the following Fourier coefficients:

  \begin{align*}
    c_{0}  &amp;amp;= \frac{11}{15}, \\
    c_{3}  &amp;amp;= c_{6} = c_{9} = c_{12} = \frac{2}{5}, \\
    c_{5}  &amp;amp;= c_{10} = \frac{1}{3}, \\
    c_{1}  &amp;amp;= c_{2} = c_{4} = c_{7} = c_{8} = c_{11} = c_{13} = c_{14} = 0.
  \end{align*}

  Calculating these Fourier coefficients by hand can be rather
  tedious.  In practice they are almost always calculated using
  numerical software, computer algebra systems or even simple code
  such as the example here:
  &lt;a href=&quot;code/fizz-buzz-fourier/fizz-buzz-fourier.py&quot;&gt;fizz-buzz-fourier.py&lt;/a&gt;.
&lt;/p&gt;
&lt;h3 id=&quot;inverse-transform&quot;&gt;Inverse Transform&lt;/h3&gt;
&lt;p&gt;
  Once the coefficients are known, we can substitute them into the
  inverse transform introduced earlier to obtain

  \begin{align*}
    f(n)
    &amp;amp;= \sum_{k = 0}^{14} c_k \, e^{i 2 \pi k n / 15} \\[1.5em]
    &amp;amp;= \frac{11}{15}
           + \frac{2}{5} \left(
             e^{i 2 \pi \cdot 3n / 15}
             + e^{i 2 \pi \cdot 6n / 15}
             + e^{i 2 \pi \cdot 9n / 15}
             + e^{i 2 \pi \cdot 12n / 15}
           \right) \\
           &amp;amp; \phantom{=\frac{11}{15}}
           + \frac{1}{3} \left(
             e^{i 2 \pi \cdot 5n / 15}
             + e^{i 2 \pi \cdot 10n / 15}
           \right) \\[1em]
    &amp;amp;= \frac{11}{15}
           + \frac{2}{5} \left(
             e^{i 2 \pi \cdot 3n / 15}
             + e^{i 2 \pi \cdot 6n / 15}
             + e^{-i 2 \pi \cdot 6n / 15}
             + e^{-i 2 \pi \cdot 3n / 15}
           \right) \\
           &amp;amp; \phantom{=\frac{11}{15}}
           + \frac{1}{3} \left(
             e^{i 2 \pi \cdot 5n / 15}
             + e^{-i 2 \pi \cdot 5n / 15}
           \right) \\[1em]
    &amp;amp;= \frac{11}{15}
       + \frac{2}{5} \left(
         2 \cos \left( \frac{2 \pi n}{5} \right)
         + 2 \cos \left( \frac{4 \pi n}{5} \right)
       \right) \\
       &amp;amp; \phantom{=\frac{11}{15}}
       + \frac{1}{3} \left(
         2 \cos \left( \frac{2 \pi n}{3} \right)
       \right) \\[1em]
    &amp;amp;= \frac{11}{15} +
       \frac{4}{5} \cos \left( \frac{2 \pi n}{5} \right) +
       \frac{4}{5} \cos \left( \frac{4 \pi n}{5} \right) +
       \frac{2}{3} \cos \left( \frac{2 \pi n}{3} \right).
  \end{align*}

  This is exactly the same expression for \( f(n) \) we obtained in
  the previous section.  We see that the Fizz Buzz index function \(
  f(n) \) can be expressed precisely using the machinery of Fourier
  analysis.
&lt;/p&gt;
&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;
  To summarise, we have defined the Fizz Buzz sequence as

  \[
    (s_{f(n)}(n))_{n = 1}^{\infty}
  \]

  where

  \[
    f(n)
    = \frac{11}{15} +
      \frac{2}{3} \cos \left( \frac{2 \pi n}{3} \right) +
      \frac{4}{5} \cos \left( \frac{2 \pi n}{5} \right) +
      \frac{4}{5} \cos \left( \frac{4 \pi n}{5} \right).
  \]

  and \( s_0(n) = n, \) \( s_1(n) = \mathtt{Fizz}, \) \( s_2(n) =
  \mathtt{Buzz} \) and \( s_3(n) = \mathtt{FizzBuzz}.  \)  A Python
  program to print the Fizz Buzz sequence based on this definition was
  presented earlier.  That program can be written more succinctly as
  follows:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;from math import cos, pi
for n in range(1, 101):
    print([n, &apos;Fizz&apos;, &apos;Buzz&apos;, &apos;FizzBuzz&apos;][round(11 / 15 + (2 / 3) * cos(2 * pi * n / 3) + (4 / 5) * (cos(2 * pi * n / 5) + cos(4 * pi * n / 5)))])&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  We can also wrap this up nicely in a shell one-liner, in case you
  want to share it with your friends and family and surprise them:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;python3 -c &apos;from math import cos, pi; [print([n, &quot;Fizz&quot;, &quot;Buzz&quot;, &quot;FizzBuzz&quot;][round(11/15 + (2/3) * cos(2*pi*n/3) + (4/5) * (cos(2*pi*n/5) + cos(4*pi*n/5)))]) for n in range(1, 101)]&apos;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  We have taken a simple counting game and turned it into a
  trigonometric construction consisting of a discrete Fourier series
  with three cosine terms and four coefficients.  None of this makes
  Fizz Buzz any easier.  Quite the contrary.  But it does show that
  every \( \mathtt{Fizz} \) and \( \mathtt{Buzz} \) now owes its
  existence to a particular set of Fourier coefficients.  We began
  with the modest goal of making this simple problem more complicated.
  I think it is safe to say that we did not fall short.
&lt;/p&gt;
<!-- ### -->
&lt;p&gt;
  &lt;a href="https://susam.net/fizz-buzz-with-cosines.html"&gt;Read on website&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/absurd.html&quot;&gt;#absurd&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/python.html&quot;&gt;#python&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/programming.html&quot;&gt;#programming&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/technology.html&quot;&gt;#technology&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/mathematics.html&quot;&gt;#mathematics&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/puzzle.html&quot;&gt;#puzzle&lt;/a&gt;
&lt;/p&gt;
<!-- END HTML -->
    </content>
  </entry>
  <entry>
    <title>Mutually Attacking Knights</title>
    <link href="https://susam.net/mutually-attacking-knights.html"/>
    <id>urn:uuid:067f9d67-e249-418b-a9b8-62b84e90d047</id>
    <updated>2025-08-11T00:00:00Z</updated>
    <content type="html">
<!-- BEGIN HTML -->
&lt;p&gt;
  How many different ways can we place two identical knights on an \(
  n \times n \) chessboard so that they attack each other?  Can we
  find a closed-form expression that gives this number?  This is the
  problem we explore in this article.
&lt;/p&gt;
&lt;h2 id=&quot;contents&quot;&gt;Contents&lt;/h2&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;#introduction&quot;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#counting-placements-as-the-board-grows&quot;&gt;Counting Placements as the Board Grows&lt;/a&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#type-a-squares&quot;&gt;Type A Squares&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#type-b-squares&quot;&gt;Type B Squares&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#type-c-squares&quot;&gt;Type C Squares&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#type-d-squares&quot;&gt;Type D Squares&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#closed-form-expression-1&quot;&gt;Closed Form Expression&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#counting-placements-for-each-square&quot;&gt;Counting Placements for Each Square&lt;/a&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#attacking-degrees-of-squares&quot;&gt;Attacking Degrees of Squares&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#from-attacking-degrees-to-counting-placements&quot;&gt;From Attacking Degrees to Counting Placements&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#closed-form-expression-2&quot;&gt;Closed Form Expression&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#counting-placements-from-minimal-attack-sections&quot;&gt;Counting Placements From Minimal Attack Sections&lt;/a&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#minimal-attack-sections&quot;&gt;Minimal Attack Sections&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#closed-form-expression-3&quot;&gt;Closed Form Expression&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#reference&quot;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;introduction&quot;&gt;Introduction&lt;/h2&gt;
&lt;p&gt;
  A knight moves two squares in one direction, then one square
  perpendicular to it, forming an L-shaped path.  If a piece occupies
  the destination square, the knight captures it.  If two knights are
  placed such that each can capture the other in a single move, then
  we say the knights attack each other.  We want to determine the
  number of ways to place two identical knights on an \( n \times n \)
  chessboard so that they attack each other.
&lt;/p&gt;
&lt;figure&gt;
  &lt;table class=&quot;chess odd&quot;&gt;
    &lt;tr&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;figcaption&gt;
    Two knights attacking each other
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  The above illustration shows just one of several ways two knights
  can attack each other on a \( 3 \times 3 \) board.  There are, in
  fact, a total of eight such placements, shown below.
&lt;/p&gt;
&lt;figure style=&quot;text-align: center&quot;&gt;
  &lt;!-- 1 --&gt;
  &lt;table class=&quot;chess odd inline&quot;&gt;
    &lt;tr&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;!-- 2 --&gt;
  &lt;table class=&quot;chess odd inline&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;!-- 3 --&gt;
  &lt;table class=&quot;chess odd inline&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;!-- 4 --&gt;
  &lt;table class=&quot;chess odd inline&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;!-- 5 --&gt;
  &lt;table class=&quot;chess odd inline&quot;&gt;
    &lt;tr&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;!-- 6 --&gt;
  &lt;table class=&quot;chess odd inline&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;!-- 7 --&gt;
  &lt;table class=&quot;chess odd inline&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;!-- 8 --&gt;
  &lt;table class=&quot;chess odd inline&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;figcaption&gt;
    All \( 8 \) ways two identical knights can attack each other on a
    \( 3 \times 3 \) board.
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  Let \( f(n) \) denote the number of ways we can place two identical
  knights on an \( n \times n \) chessboard such that they attack each
  other, where \( n \ge 1.  \)
&lt;/p&gt;
&lt;p&gt;
  A \( 1 \times 1 \) board has room for only one knight, so we define
  \( f(1) = 0.  \)  On a \( 2 \times 2 \) board, a knight cannot move
  two squares in any direction and therefore cannot attack.
  Therefore, \( f(2) = 0.  \)  To summarise,

  \[
    f(1) = f(2) = 0.
  \]

  From the illustration above, we see that \( f(3) = 8.  \)  We want to
  find a closed-form expression for \( f(n).  \)
&lt;/p&gt;
&lt;p&gt;
  We will analyse this problem from various perspectives.  We begin
  with a couple of needlessly complicated approaches, followed by a
  simple and elegant solution.  While I personally enjoy these
  long-winded explorations, if you prefer a more direct solution,
  please skip ahead
  to &lt;a href=&quot;#counting-placements-from-minimal-attack-sections&quot;&gt;Counting
  Placements From Minimal Attack Sections&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
  Before we proceed, let us introduce the term &lt;em&gt;mutually attacking
  knight placement&lt;/em&gt; to mean a placement of two knights on the
  chessboard such that they attack each other.  Unless stated
  otherwise, the two knights are identical.  This term will serve as a
  convenient shorthand for referring to such placements.
&lt;/p&gt;
&lt;h2 id=&quot;counting-placements-as-the-board-grows&quot;&gt;Counting Placements as the Board Grows&lt;/h2&gt;
&lt;p&gt;
  We now turn to the needlessly complicated solution promised in the
  previous section.  We analyse the &lt;em&gt;new&lt;/em&gt; mutually attacking
  knight placements introduced when an existing board is enlarged by
  adding a row and a column.
&lt;/p&gt;
&lt;p&gt;
  Let us define

  \[
    \Delta f(n) = f(n) - f(n - 1)
  \]

  for \( n \ge 2, \) so that \( \Delta f(n) \) denotes the new
  mutually attacking knight placements introduced when an \( (n - 1)
  \times (n - 1) \) board is expanded to size \( n \times n \) by
  adding one row and one column.
&lt;/p&gt;
&lt;p&gt;
  For brevity, we will avoid restating the process of enlarging an \(
  (n - 1) \times (n - 1) \) board to an \( n \times n \) board by
  adding one row and one column whenever we refer to new placements.
  Instead, we use the term &lt;em&gt;new placements&lt;/em&gt; on an
  \( n \times n \) board to refer to \( \Delta f(n).  \)  It is to be
  understood that these new placements are the mutually attacking
  knight placements introduced by enlarging the board from size \( (n
  - 1) \times (n - 1) \) to \( n \times n.  \)
&lt;/p&gt;
&lt;p&gt;
  Without loss of generality, suppose the new row and column are added
  to the bottom and right respectively.  We already know that

  \begin{align*}
    \Delta f(2) &amp;amp; = f(2) - f(1) = 0 - 0 = 0, \\
    \Delta f(3) &amp;amp; = f(3) - f(2) = 8 - 0 = 8.  \\
  \end{align*}

  We will now find \( \Delta f(n) \) for \( n \ge 4.  \)  To do this,
  we first categorise the newly added squares due to board expansion,
  into four types, as illustrated below.
&lt;/p&gt;
&lt;figure&gt;
  &lt;table class=&quot;chess&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;A&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;B&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;C&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;C&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;D&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td class=&quot;em&quot;&gt;A&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;B&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;C&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;C&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;D&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;A&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;figcaption&gt;
    New squares, labelled by type, as the board size increases from \(
    5 \times 5 \) to \( 6 \times 6 \)
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  Here is a brief description of each square type:
&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
    Type A squares are the three new corner squares.
  &lt;/li&gt;
  &lt;li&gt;
    Type B squares are the two new squares adjacent to type A squares
    at the top and left edges.
  &lt;/li&gt;
  &lt;li&gt;
    Type C squares are the new squares that are &lt;em&gt;not&lt;/em&gt; adjacent
    to any type A square.  If the new board has dimensions \( n \times
    n, \) where \( n \ge 4, \) then there are exactly \( 2n - 8 \)
    squares of type C.
  &lt;/li&gt;
  &lt;li&gt;
    Type D squares are the two new squares adjacent to the
    bottom-right type A square.
  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
  We now calculate how many new mutually attacking knight placements
  are introduced by these additional squares as the board expands.  We
  proceed with a case-by-case analysis for each square type.
&lt;/p&gt;
&lt;h3 id=&quot;type-a-squares&quot;&gt;Type A Squares&lt;/h3&gt;
&lt;p&gt;
  There are three squares of type A.  If we place one knight on a type
  A square, there are two positions for the second knight such that
  the two knights attack each other.
&lt;/p&gt;
&lt;figure&gt;
  &lt;table class=&quot;chess odd&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&amp;cross;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&amp;cross;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td class=&quot;black knight em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;figcaption&gt;
    Knights on type A squares, with squares attacked by the top knight
    marked with crosses
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  Since there are three such squares, we get a total of \( 3 \times 2
  = 6 \) new mutually attacking knight placements.
&lt;/p&gt;
&lt;h3 id=&quot;type-b-squares&quot;&gt;Type B Squares&lt;/h3&gt;
&lt;p&gt;
  There are two squares of type B.  If we place one knight on a type B
  square, there are three positions for the second knight such that
  the two knights attack each other.
&lt;/p&gt;
&lt;figure&gt;
  &lt;table class=&quot;chess odd&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&amp;cross;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&amp;cross;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&amp;cross;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;figcaption&gt;
    Knights on type B squares, with squares attacked by the top knight
    marked with crosses
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  Since there are two such squares, we get a total of \( 2 \times 3 =
  6 \) new mutually attacking knight placements.
&lt;/p&gt;
&lt;h3 id=&quot;type-c-squares&quot;&gt;Type C Squares&lt;/h3&gt;
&lt;p&gt;
  The number of type C squares depends on the board size.  When we
  increase the size of a board from \( (n - 1) \times (n - 1) \) to
  \(n \times n, \) where \( n \ge 4, \) we add \( n^2 - (n - 1)^2 = 2n
  - 1 \) new squares.  Among these, \( 3 \) are of type A, \( 2 \) are
  of type B and \( 2 \) are of type D.  That gives us a total of \(
  7 \) squares of type A, B or D.  The remaining \( 2n - 1 - 7 = 2n -
  8 \) squares are therefore of type C.  Note that when the board size
  increases from \( 3 \times 3 \) to \( 4 \times 4, \) there are \( 2
  \times 4 - 8 = 0 \) squares of type C.
&lt;/p&gt;
&lt;figure&gt;
  &lt;table class=&quot;chess&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;A&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;B&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;D&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td class=&quot;em&quot;&gt;A&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;B&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;D&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;A&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;figcaption&gt;
    A \( 4 \times 4 \) board has no type C squares.
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  However, for a board of size \( 5 \times 5 \) or greater, there is a
  positive number of type C squares since \( 2n - 8 \gt 0 \) if and
  only if \( n \gt 4.  \)
&lt;/p&gt;
&lt;figure&gt;
  &lt;table class=&quot;chess&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;A&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;B&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;C&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;D&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td class=&quot;em&quot;&gt;A&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;B&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;C&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;D&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;A&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;figcaption&gt;
    A \( 5 \times 5 \) board has one type C square.
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  If we place one knight on a type C square, there are four positions
  for the second knight such that the two knights attack each other.
&lt;/p&gt;
&lt;figure&gt;
  &lt;table class=&quot;chess odd&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&amp;cross;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&amp;cross;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&amp;cross;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&amp;cross;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;figcaption&gt;
    Knights on type C squares, with squares attacked by the top knight
    marked with crosses
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  Since there are \( 2n - 8 \) such squares, we get a total of \( 4(2n
  - 8) = 8(n - 4) \) new mutually attacking knight placements.
&lt;/p&gt;
&lt;h3 id=&quot;type-d-squares&quot;&gt;Type D Squares&lt;/h3&gt;
&lt;p&gt;
  There are two squares of type D.  As with type B squares, placing
  one knight on a type D square yields three positions for the second
  knight such that the two knights attack each other.  This gives \( 2
  \times 3 = 6 \) &lt;em&gt;potentially&lt;/em&gt; new placements.
&lt;/p&gt;
&lt;figure&gt;
  &lt;table class=&quot;chess odd&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&amp;cross;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&amp;cross;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&amp;cross;&lt;/td&gt;
      &lt;td class=&quot;black knight em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;figcaption&gt;
    Knights on type D squares, with squares attacked by the top knight
    marked with crosses
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  However, unlike type B squares, not all of these placements are
  &lt;em&gt;new&lt;/em&gt;.  The two placements where one knight is on the right
  edge and the other on the bottom edge were already counted in a
  previous subsection.
&lt;/p&gt;
&lt;figure&gt;
  &lt;table class=&quot;chess inline&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;table class=&quot;chess inline&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;figcaption&gt;
    Placements already counted while analysing placements involving a
    knight on a type B square of the \( 4 \times 4 \) board
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  For example, when we increase the board size from \( 3 \times 3 \)
  to \( 4 \times 4, \) both the placements described in the previous
  paragraph appear while analysing the placements with a knight on a
  type B square.  More generally, for any board of size
  \( n \times n \) with \( n \ge 5, \) these placements occur while
  analysing the placements with a knight on a type C square.
  Therefore the total number of new mutually attacking knight
  placements is \( 2 \times 3 - 2 = 4.  \)
&lt;/p&gt;
&lt;figure&gt;
  &lt;table class=&quot;chess odd inline&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;table class=&quot;chess odd inline&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;figcaption&gt;
    Placements already counted while analysing placements involving a
    knight on a type C square of an \( n \times n \) board, where \( n
    \ge 5 \)
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  Another way to describe this result is to observe that when one
  knight is placed on a type D square, only two positions for the
  second knight yield &lt;em&gt;new&lt;/em&gt; mutually attacking knight
  placements.  Since there are two type \( D \) squares, we get a
  total of \( 2 \times 2 = 4 \) new mutually attacking knight
  placements.
&lt;/p&gt;
&lt;figure&gt;
  &lt;table class=&quot;chess odd&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&amp;cross;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&amp;cross;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight em&quot;&gt;&lt;/td&gt;
      &lt;td class=&quot;em&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;figcaption&gt;
    Knights on type D squares, with squares attacked by the top knight
    that yield &lt;em&gt;new&lt;/em&gt; mutually attacking knight placements
    marked with crosses
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;h3 id=&quot;closed-form-expression-1&quot;&gt;Closed Form Expression&lt;/h3&gt;
&lt;p&gt;
  If we add the number of new mutually attacking knight placements
  found in each of the cases above, we get

  \[
    \Delta f(n) = 6 + 6 + 8(n - 4) + 4 = 8(n - 2)
  \]

  new mutually attacking knight placements as the board size increases
  from \( (n - 1) \times (n - 1) \) to \( n \times n, \) where \( n
  \ge 4.  \)  We already know that \( \Delta f(2) = 0 \) and \( \Delta
  f(3) = 8.  \)  Surprisingly, the above formula produces the correct
  values for those cases as well.  Therefore, we can generalise this
  result as

  \[
    \Delta f(n) = 8(n - 2)
  \]

  for all \( n \ge 2.  \)  We can now calculate \( f(n) \) for \( n \ge
  1 \) as follows:

  \begin{align*}
    f(n)
    &amp;amp; = \sum_{k = 1}^n f(k) - \sum_{k = 1}^{n - 1} f(k) \\
    &amp;amp; = \sum_{k = 1}^n f(k) - \sum_{k = 2}^n f(k - 1) \\
    &amp;amp; = f(1) + \sum_{k = 2}^n (f(k) - f(k - 1)) \\
    &amp;amp; = f(1) + \sum_{k = 2}^n \Delta f(k) \\
    &amp;amp; = 0 + \sum_{k = 2}^n 8(k - 2) \\
    &amp;amp; = 8 \sum_{k = 0}^{n - 2} k \\
    &amp;amp; = \frac{8(n - 2)(n - 1)}{2} \\
    &amp;amp; = 4(n - 1)(n - 2).
  \end{align*}

  To summarise, we now have a closed form expression for \( f(n).  \)
  For all \( n \ge 1, \) we have

  \[
    f(n) = 4(n - 1)(n - 2).
  \]
&lt;/p&gt;
&lt;h2 id=&quot;counting-placements-for-each-square&quot;&gt;Counting Placements for Each Square&lt;/h2&gt;
&lt;p&gt;
  The previous section took a long-winded path to arrive at a closed
  form expression for \( f(n).  \)  In this section, we will reach the
  same result that is still a bit drawn out, but not quite as much as
  before.
&lt;/p&gt;
&lt;p&gt;
  This time, instead of looking only at the new squares created when
  the board grows, we consider &lt;em&gt;every&lt;/em&gt; square on the board.  To
  make the counting easier, we no longer treat the knights as
  identical.  We first work with two distinct knights, count the
  mutually attacking knight placements and then divide the total by \(
  2 \) to get the result for identical knights.
&lt;/p&gt;
&lt;h3 id=&quot;attacking-degrees-of-squares&quot;&gt;Attacking Degrees of Squares&lt;/h3&gt;
&lt;p&gt;
  Here, we introduce the term &lt;em&gt;attacking degree of a square&lt;/em&gt; to
  mean the number of squares a knight can move to from that square in
  a single move.  In other words, the attacking degree of a square is
  the number of squares that would be attacked if a knight were placed
  on it.  For example, the corner squares have an attacking degree of
  \( 2.  \)
&lt;/p&gt;
&lt;figure&gt;
  &lt;table class=&quot;chess&quot;&gt;
    &lt;tr&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&amp;cross;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&amp;cross;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;figcaption&gt;
    The attacking degree of a corner square is \( 2 \) since a knight
    can attack two squares from it
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  Let us now label each square with its attacking degree.  A \( 1
  \times 1 \) board has only one square of attacking degree \( 0 \)
  since a knight placed on it has nothing to attack.  Similarly, each
  square of a \( 2 \times 2 \) board has attacking degree \( 0 \) too.
&lt;/p&gt;
&lt;figure&gt;
  &lt;table class=&quot;chess odd inline&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;0&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;table class=&quot;chess inline&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;0&lt;/td&gt;
      &lt;td&gt;0&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;0&lt;/td&gt;
      &lt;td&gt;0&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;figcaption&gt;
    Attacking degrees of all squares are zero on \( 1 \times 1 \) and
    \( 2 \times 2 \) boards
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  On a \( 3 \times 3 \) board, all squares have attacking degree
  \( 2 \) except the centre square, whose attacking degree is \( 0.  \)
  In other words, placing a knight on any square other than the middle
  one gives exactly two possible positions for the other knight so
  that they attack each other.
&lt;/p&gt;
&lt;figure&gt;
  &lt;table class=&quot;chess odd&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;2&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;0&lt;/td&gt;
      &lt;td&gt;2&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;2&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;figcaption&gt;
    Attacking degrees of all squares on a \( 3 \times 3 \) board
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  With eight such squares, we get \( 8 \times 2 = 16 \) mutually
  attacking knight placements when the two knights are distinct.  If
  we divide this number by \( 2, \) we get \( 8 \) which is indeed the
  number of mutually attacking knight placements on a \( 3 \times 3 \)
  board when the two knights are identical.  This matches the earlier
  result \( f(3) = 8.  \)
&lt;/p&gt;
&lt;h3 id=&quot;from-attacking-degrees-to-counting-placements&quot;&gt;From Attacking Degrees to Counting Placements&lt;/h3&gt;
&lt;p&gt;
  Let \( g(n) \) be the number of mutually attacking knight placements
  on an \( n \times n \) board when the knights are distinct.  Then \(
  g(n) \) is simply the sum of the attacking degrees of all squares on
  the board.  As before, let \( f(n) \) denote the number of mutually
  attacking knight placements on an \( n \times n \) board when the
  two knights are identical.  We will now show that
  \( f(n) = g(n)/2.  \)
&lt;/p&gt;
&lt;p&gt;
  Label all squares of the \( n \times n \) board as \( S_1, S_2,
  \dots, S_{n^2} \) in any fixed order.  Label the two distinct
  knights as \( N_1 \) and \( N_2.  \)  We represent each mutually
  attacking knight placement as an ordered pair \( (S_i, S_j) \) if \(
  N_1 \) is on \( S_i \) and \( N_2 \) is on \( S_j, \) with the two
  knights attacking each other.  Here \( 1 \le i, j \le n^2 \) and \(
  i \ne j.  \)
&lt;/p&gt;
&lt;p&gt;
  Let \( M \) be the set of all mutually attacking knight placements
  for distinct knights on an \( n \times n \) board.  Then

  \[
    g(n) = \lvert M \rvert.
  \]

  If \( (S_i, S_j) \) is a mutually attacking knight placement of the
  distinct knights \( N_1 \) and \( N_2 \) for some \( i \) and
  \( j \) with \( 1 \le i, j \le n^2 \) and \( i \ne j, \) then \(
  (S_j, S_i) \) is also a mutually attacking knight placement, since
  swapping the positions of the two mutually attacking knights still
  yields a valid mutually attacking placement.  Therefore

  \[
    (S_i, S_j) \in M \iff (S_j, S_i) \in M.
  \]

  Each ordered placement \( (S_i, S_j) \) in \( M \) is thus paired
  with the ordered placement \( (S_j, S_i).  \)  When the knights are
  identical, the two arrangements are indistinguishable and count as
  one placement.  Hence, the number of mutually attacking placements
  for identical knights is exactly half of the number for distinct
  knights, i.e.

  \[
    f(n) = \frac{g(n)}{2}.
  \]

  The next subsection focuses on calculating \( g(n), \) from which \(
  f(n) \) follows immediately by the above formula.
&lt;/p&gt;
&lt;h3 id=&quot;closed-form-expression-2&quot;&gt;Closed Form Expression&lt;/h3&gt;
&lt;p&gt;
  As noted in the previous section, the number of mutually attacking
  knight placements for two distinct knights on an \( n \times n \)
  board is simply the sum of attacking degrees of all squares on the
  board.  If we label each square as discussed in the previous section
  and use the notation \( \deg(S_i) \) for the attacking degree of the
  square labelled \( S_i, \) where \( 1 \le i \le n^2, \) then

  \[
    g(n) = \sum_{i=1}^{n^2} \deg(S_i).
  \]

  Recall that the attacking degree of a square is the number of
  squares a knight could attack if it were placed there.  Earlier, we
  saw that on a \( 3 \times 3 \) board, all squares except the centre
  one have attacking degree \( 2, \) which gives \( g(3) = 8 \times 2
  = 16 \) and \( f(3) = g(3)/2 = 8.  \)  Let us now write down the
  attacking degrees of all squares on a \( 4 \times 4 \) board.
&lt;/p&gt;
&lt;figure&gt;
  &lt;table class=&quot;chess&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;2&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;3&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;3&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;2&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;figcaption&gt;
    Attacking degrees of all squares on a \( 4 \times 4 \) board
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  From the above illustration we get

  \begin{align*}
    g(4) &amp;amp; = 4 \times 2 + 8 \times 3 + 4 \times 4 = 48, \\
    f(4) &amp;amp; = g(4)/2 = 24.
  \end{align*}

  A more general pattern emerges if we consider a larger board, such
  as a \( 6 \times 6 \) board.
&lt;/p&gt;
&lt;figure&gt;
  &lt;table class=&quot;chess&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;2&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;6&lt;/td&gt;
      &lt;td&gt;6&lt;/td&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;3&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;6&lt;/td&gt;
      &lt;td&gt;8&lt;/td&gt;
      &lt;td&gt;8&lt;/td&gt;
      &lt;td&gt;6&lt;/td&gt;
      &lt;td&gt;4&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;6&lt;/td&gt;
      &lt;td&gt;8&lt;/td&gt;
      &lt;td&gt;8&lt;/td&gt;
      &lt;td&gt;6&lt;/td&gt;
      &lt;td&gt;4&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;6&lt;/td&gt;
      &lt;td&gt;6&lt;/td&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;3&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;2&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;figcaption&gt;
    Attacking degrees of all squares on a \( 6 \times 6 \) board
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  From this illustration, we get

  \begin{align*}
    g(6) &amp;amp; = 4 \times 2 + 8 \times 3 + 12 \times 4 + 8 \times 6 + 4 \times 8 = 160.  \\
    f(6) &amp;amp; = g(6)/2 = 80.
  \end{align*}

  Let us find a general formula now for \( n \ge 4.  \)  We introduce
  one more notation.  Let \( D_k(n) \) denote the sum of the attacking
  degrees of all squares of attacking degree \( k \) on an \( n \times
  n \) board, i.e.

  \[
    D_k(n) = \sum_{\mathclap{\deg(S_i) = k}} \deg(S_i).
  \]

  Since the only attacking degrees the squares can have are \( 2, 3,
  4, 6 \) and \( 8, \) the sum of the attacking degrees of all squares
  can be written as

  \[
    g(n) = D_2(n) + D_3(n) + D_4(n) + D_6(n) + D_8(n).
  \]

  There are exactly four squares of attacking degree \( 2.  \)  These
  are the corner ones.  Therefore,

  \[
    D_2(n) = 4 \times 2 = 8.
  \]

  The eight squares adjacent to the corner squares have attacking
  degree \( 3.  \)  Therefore,

  \[
    D_3(n) = 8 \times 3 = 24.
  \]

  Let us define an &lt;em&gt;inner corner square&lt;/em&gt; as one that shares a
  corner with a corner square but not an edge with it.  There are four
  inner corner squares and each has attacking degree \( 4.  \)
  Further, each row and column on the outer edge contains \( n - 4 \)
  additional squares with attacking degree \( 4.  \)  Therefore,

  \[
    D_4(n) = (4 + 4(n - 4))(4) = 16(n - 3).
  \]

  Consider a row or column that contains two inner corner squares of
  attacking degree \( 4.  \)  All \( n - 4 \) squares between the inner
  corner squares have attacking degree \( 6.  \)  There are two such
  rows and two such columns.  Therefore,

  \[
    D_6(n) = 4(n - 4)(6) = 24(n - 4).
  \]

  We have counted the attacking degrees of all squares in the first
  two columns and rows as well as the last two columns and rows.  We
  are left with \( (n - 4)^2 \) squares in the middle and they all
  have attacking degree \( 8.  \)  Therefore,

  \[
    D_8(n) = 8(n - 4)^2.
  \]

  Therefore,

  \begin{align*}
    g(n)
    &amp;amp; = D_2(n) + D_3(n) + D_4(n) + D_6(n) + D_8(n) \\
    &amp;amp; = 8 + 24 + 16(n - 3) + 24(n - 4) + 8(n - 4)^2 \\
    &amp;amp; = 8(n - 1)(n - 2).
  \end{align*}

  Even though we assumed \( n \ge 4 \) while obtaining the above
  formula, remarkably, it gives us the correct values for \( n = 1,
  2 \) and \( 3.  \)  The number of mutually attacking knight
  placements for distinct knights on an \( n \times n \) board is \(
  0 \) if \( n = 1 \) or \( 2.  \)  It is \( 16 \) if \( n = 3.  \)
  Indeed the above formula gives us

  \[
    g(1) = g(2) = 0, \quad g(3) = 16.
  \]

  Therefore, we can now generalise the above result as

  \[
    g(n) = 8(n - 1)(n - 2)
  \]

  for all \( n \ge 1.  \)  Therefore, for all \( n \ge 1, \)

  \[
    f(n) = \frac{g(n)}{2} = 4(n - 1)(n - 2).
  \]
&lt;/p&gt;
&lt;h2 id=&quot;counting-placements-from-minimal-attack-sections&quot;&gt;Counting Placements From Minimal Attack Sections&lt;/h2&gt;
&lt;p&gt;
  Finally, in this section, we take a look at a simple and elegant
  solution that arrives at the closed-form solution in a more direct
  manner.  The analysis begins by looking at the smallest section of
  the board where two knights can attack each other.
&lt;/p&gt;
&lt;h3 id=&quot;minimal-attack-sections&quot;&gt;Minimal Attack Sections&lt;/h3&gt;
&lt;p&gt;
  Consider a \( 2 \times 3 \) section of a board of size
  \( 3 \times 3 \) or larger.  Such a section has exactly two mutually
  attacking knight placements.
&lt;/p&gt;
&lt;figure&gt;
  &lt;table class=&quot;chess inline&quot;&gt;
    &lt;tr&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;table class=&quot;chess inline&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;figcaption&gt;
    Two mutually attacking knight placements on a \( 2 \times 3 \)
    section of a board
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  Similarly, a \( 3 \times 2 \) section of a board also has exactly
  two mutually attacking knight placements.
&lt;/p&gt;
&lt;figure&gt;
  &lt;table class=&quot;chess odd inline&quot;&gt;
    &lt;tr&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;table class=&quot;chess odd inline&quot;&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td class=&quot;black knight&quot;&gt;&lt;/td&gt;
      &lt;td&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
  &lt;figcaption&gt;
    Two mutually attacking knight placements on a \( 3 \times 2 \)
    section of a board
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  We call these \( 2 \times 3 \) and \( 3 \times 2 \) sections
  the &lt;em&gt;minimal attack sections&lt;/em&gt; of a board, since no smaller
  section can contain a mutually attacking knight placement.
&lt;/p&gt;
&lt;p&gt;
  Two distinct \( 2 \times 3 \) sections can share at most a \( 1
  \times 3 \) section, which is smaller than a minimal attack section.
  Consequently, no mutually attacking knight placement can be common
  to two distinct \( 2 \times 3 \) sections of a board.
&lt;/p&gt;
&lt;p&gt;
  Similarly, two distinct \( 3 \times 2 \) sections can share at most
  a \( 3 \times 1 \) section, again too small to contain a minimal
  attack section.  Therefore, they share no mutually attacking knight
  placement.
&lt;/p&gt;
&lt;p&gt;
  A \( 2 \times 3 \) section and a \( 3 \times 2 \) section can share
  at most a \( 2 \times 2 \) section, which is still smaller than a
  minimal attack section, so they share no mutually attacking knight
  placement either.
&lt;/p&gt;
&lt;p&gt;
  To summarise, any two minimal attack sections of the board yield
  distinct pairs of mutually attacking knight placements.  The total
  number of such placements is therefore exactly twice the number of
  minimal attack sections on the board.
&lt;/p&gt;
&lt;h3 id=&quot;closed-form-expression-3&quot;&gt;Closed Form Expression&lt;/h3&gt;
&lt;p&gt;
  In an \( n \times n \) board where \( n \ge 3, \) the left edge of a
  \( 2 \times 3 \) section can be placed in any one of the first \( n
  - 2 \) columns of the board.  Similarly, the top edge of such a
  section can be placed in any one of the first \( n - 1 \) rows of
  the board.  Therefore, the total number of distinct \( 2 \times 3 \)
  sections on the board is \( (n - 2)(n - 1).  \)
&lt;/p&gt;
&lt;p&gt;
  By similar reasoning, the number of distinct \( 3 \times 2 \)
  sections on an \( n \times n \) board, where \( n \ge 3, \) is also
  \( (n - 1)(n - 2).  \)
&lt;/p&gt;
&lt;p&gt;
  Let \( h(n) \) be the total number of minimal attack sections we can
  find on an \( n \times n \) board where \( n \ge 1.  \)  From the
  discussion in the previous two paragraphs, we know that \( h(n) =
  2(n - 1)(n - 2) \) for \( n \ge 3.  \)  Further, this formula for \(
  h(n) \) works for \( n = 1 \) and \( n = 2 \) as well since \( h(1)
  = h(2) = 0 \) and indeed a \( 1 \times 1 \) board or a
  \( 2 \times 2 \) board is too small to contain any minimal attack
  sections.  Therefore, for all \( n \ge 1, \) we get

  \[
    h(n) = 2(n - 1)(n - 2).
  \]

  Since each minimal attack section yields two mutually attacking
  knight placements, the total number of mutually attacking knight
  placements on an \( n \times n \) board is

  \[
    f(n) = 2h(n) = 4(n - 1)(n - 2)
  \]

  for all \( n \ge 1.  \)
&lt;/p&gt;
&lt;h2 id=&quot;reference&quot;&gt;References&lt;/h2&gt;
&lt;ul&gt;
  &lt;li&gt;
    &lt;a href=&quot;https://cses.fi/problemset/task/1072&quot;&gt;Two Knights&lt;/a&gt;
    from the CSES Problem Set
  &lt;/li&gt;
  &lt;li&gt;
    &lt;a href=&quot;https://mathworld.wolfram.com/KnightGraph.html&quot;&gt;Knight Graph&lt;/a&gt;
    by Eric W. Weisstein
  &lt;/li&gt;
  &lt;li&gt;
    &lt;a href=&quot;https://oeis.org/A033996&quot;&gt;OEIS Entry A033996&lt;/a&gt;
    by N. J. A. Sloane
  &lt;/li&gt;
  &lt;li&gt;
    &lt;a href=&quot;https://oeis.org/A172132&quot;&gt;OEIS Entry A172132&lt;/a&gt;
    by Vaclav Kotesovec
  &lt;/li&gt;
&lt;/ul&gt;
<!-- ### -->
&lt;p&gt;
  &lt;a href="https://susam.net/mutually-attacking-knights.html"&gt;Read on website&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/mathematics.html&quot;&gt;#mathematics&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/puzzle.html&quot;&gt;#puzzle&lt;/a&gt;
&lt;/p&gt;
<!-- END HTML -->
    </content>
  </entry>
  <entry>
    <title>Zigzag Number Spiral</title>
    <link href="https://susam.net/zigzag-number-spiral.html"/>
    <id>urn:uuid:3159680a-7c7e-49d3-b6ec-51cc2a6030a9</id>
    <updated>2025-07-27T00:00:00Z</updated>
    <content type="html">
<!-- BEGIN HTML -->
&lt;div style=&quot;display: none&quot;&gt;
  \[
    \gdef\lf{\hspace{-5mm}\leftarrow\hspace{-5mm}}
    \gdef\rt{\hspace{-5mm}\rightarrow\hspace{-5mm}}
    \gdef\up{\uparrow}
    \gdef\dn{\downarrow}
    \gdef\sp{}
    \gdef\cd{\cdots}
    \gdef\vd{\vdots}
    \gdef\dd{\ddots}
    \gdef\arraystretch{1.2}
    \gdef\hl{\small\blacktriangleright}
  \]
&lt;/div&gt;
&lt;p&gt;
  Consider the following infinite grid of numbers, where the numbers
  are arranged in a spiral-like manner, but the spiral reverses
  direction each time it reaches the edge of the grid:

  \begin{array}{rcrcrcrcrl}
      1 &amp;amp; \rt &amp;amp;   2 &amp;amp; \sp &amp;amp;   9 &amp;amp; \rt &amp;amp;  10 &amp;amp; \sp &amp;amp;  25 &amp;amp; \cd \\
    \sp &amp;amp; \sp &amp;amp; \dn &amp;amp; \sp &amp;amp; \up &amp;amp; \sp &amp;amp; \dn &amp;amp; \sp &amp;amp; \up &amp;amp; \sp \\
      4 &amp;amp; \lf &amp;amp;   3 &amp;amp; \sp &amp;amp;   8 &amp;amp; \sp &amp;amp;  11 &amp;amp; \sp &amp;amp;  24 &amp;amp; \cd \\
    \dn &amp;amp; \sp &amp;amp; \sp &amp;amp; \sp &amp;amp; \up &amp;amp; \sp &amp;amp; \dn &amp;amp; \sp &amp;amp; \up &amp;amp; \sp \\
      5 &amp;amp; \rt &amp;amp;   6 &amp;amp; \rt &amp;amp;   7 &amp;amp; \sp &amp;amp;  12 &amp;amp; \sp &amp;amp;  23 &amp;amp; \cd \\
    \sp &amp;amp; \sp &amp;amp; \sp &amp;amp; \sp &amp;amp; \sp &amp;amp; \sp &amp;amp; \dn &amp;amp; \sp &amp;amp; \up &amp;amp; \sp \\
     16 &amp;amp; \lf &amp;amp;  15 &amp;amp; \lf &amp;amp;  14 &amp;amp; \lf &amp;amp;  13 &amp;amp; \sp &amp;amp;  22 &amp;amp; \cd \\
    \dn &amp;amp; \sp &amp;amp; \sp &amp;amp; \sp &amp;amp; \sp &amp;amp; \sp &amp;amp; \sp &amp;amp; \sp &amp;amp; \up &amp;amp; \sp \\
     17 &amp;amp; \rt &amp;amp;  18 &amp;amp; \rt &amp;amp;  19 &amp;amp; \rt &amp;amp;  20 &amp;amp; \rt &amp;amp;  21 &amp;amp; \cd \\
    \vd &amp;amp; \sp &amp;amp; \vd &amp;amp; \sp &amp;amp; \vd &amp;amp; \sp &amp;amp; \vd &amp;amp; \sp &amp;amp; \vd &amp;amp; \dd
  \end{array}

  Can we find a closed-form expression that tells us the number at the
  \( m \)th row and \( n \)th column?
&lt;/p&gt;
&lt;h2 id=&quot;contents&quot;&gt;Contents&lt;/h2&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;#introduction&quot;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#patterns-on-the-edges&quot;&gt;Patterns on the Edges&lt;/a&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#computing-edge-numbers&quot;&gt;Computing Edge Numbers&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#computing-all-grid-numbers-1&quot;&gt;Computing All Grid Numbers&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#closed-form-expression-1&quot;&gt;Closed Form Expression&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#patterns-on-the-diagonal&quot;&gt;Patterns on the Diagonal&lt;/a&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#computing-diagonal-numbers&quot;&gt;Computing Diagonal Numbers&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#computing-all-grid-numbers-2&quot;&gt;Computing All Grid Numbers&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#closed-form-expression-2&quot;&gt;Closed Form Expression&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#references&quot;&gt;References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;introduction&quot;&gt;Introduction&lt;/h2&gt;
&lt;p&gt;
  Before we explore this problem further, let us rewrite the zigzag
  number spiral grid in a cleaner form, omitting the arrows:

  \begin{array}{rrrrrl}
      1 &amp;amp;   2 &amp;amp;   9  &amp;amp;  10 &amp;amp;  25 &amp;amp; \cd \\
      4 &amp;amp;   3 &amp;amp;   8  &amp;amp;  11 &amp;amp;  24 &amp;amp; \cd \\
      5 &amp;amp;   6 &amp;amp;   7  &amp;amp;  12 &amp;amp;  23 &amp;amp; \cd \\
     16 &amp;amp;  15 &amp;amp;  14  &amp;amp;  13 &amp;amp;  22 &amp;amp; \cd \\
     17 &amp;amp;  18 &amp;amp;  19  &amp;amp;  20 &amp;amp;  21 &amp;amp; \cd \\
    \vd &amp;amp; \vd &amp;amp; \vd  &amp;amp; \vd &amp;amp; \vd &amp;amp; \dd
  \end{array}

  Let \( f(m, n) \) denote the number at the \( m \)th row and
  \( n \)th column.  For example, \( f(1, 1) = 1 \) and \( f(2, 5) =
  24.  \)  We want to find a closed-form expression for \( f(m, n).  \)
&lt;/p&gt;
&lt;p&gt;
  Let us first clarify what we mean by a &lt;em&gt;closed-form
  expression&lt;/em&gt;.  There is no universal definition of a closed-form
  expression, but the term typically refers to a mathematical
  expression involving variables and constants, built using a finite
  combination of basic operations: addition, subtraction,
  multiplication, division, integer exponents, roots with integer
  index and functions such as exponentials, logarithms and
  trigonometric functions.
&lt;/p&gt;
&lt;p&gt;
  In this article, however, we need only addition, subtraction,
  division, squares and square roots.  This may be a bit of a spoiler,
  but I must mention that the \( \max \) function appears in the
  closed-form expressions we are about to see.  If you are concerned
  about whether functions like \( \max \) and \( \min \) are permitted
  in such expressions, note that

  \begin{align*}
    \max(m, n) &amp;amp; = \frac{m + n + \sqrt{(m - n)^2}}{2}, \\
    \min(m, n) &amp;amp; = \frac{m + n - \sqrt{(m - n)^2}}{2}.
  \end{align*}

  So \( \max \) and \( \min \) are simply shorthand for expressions
  involving addition, subtraction, division, squares and square roots.
  In the discussion that follows, we will use only the \( \max \)
  function.
&lt;/p&gt;
&lt;h2 id=&quot;patterns-on-the-edges&quot;&gt;Patterns on the Edges&lt;/h2&gt;
&lt;p&gt;
  Let us begin by analysing the edge numbers.  Number the rows as \(
  1, 2, 3 \dots \) and the columns likewise.  Observe where the spiral
  touches the left edge and changes direction.  This happens only on
  even-numbered rows.  Similarly, each time the spiral touches the top
  edge and changes direction, it does so on odd-numbered columns.  In
  the following subsections, we take a closer look at this behaviour
  of the spiral.
&lt;/p&gt;
&lt;p&gt;
  I should mention that this section takes a rather long path to
  arrive at the closed-form solution.  Personally, I enjoy such long
  tours.  If you prefer a more direct approach, feel free to skip
  ahead to
  &lt;a href=&quot;#patterns-on-the-diagonal&quot;&gt;Patterns on the Diagonal&lt;/a&gt; for
  a shorter discussion that reaches the same result.
&lt;/p&gt;
&lt;h3 id=&quot;computing-edge-numbers&quot;&gt;Computing Edge Numbers&lt;/h3&gt;
&lt;p&gt;
  Each time the spiral reaches the left edge of the grid, it does so
  at some \( m \)th row where \( m \) is even.  The \( m \times m \)
  subgrid formed by the first \( m \) rows and the first \( m \)
  columns contains \( m^2 \) consecutive numbers.  Since the numbers
  strictly increase as the spiral grows, the largest of these
  \( m^2 \) numbers must appear at the position where the spiral
  touches the left edge.  This is illustrated in the figure below.
&lt;/p&gt;
&lt;figure&gt;
  \begin{array}{rrrr:rl}
     1     &amp;amp;   2 &amp;amp;   9  &amp;amp;  10 &amp;amp;  25 &amp;amp; \cd \\
     4     &amp;amp;   3 &amp;amp;   8  &amp;amp;  11 &amp;amp;  24 &amp;amp; \cd \\
     5     &amp;amp;   6 &amp;amp;   7  &amp;amp;  12 &amp;amp;  23 &amp;amp; \cd \\
    \hl 16 &amp;amp;  15 &amp;amp;  14  &amp;amp;  13 &amp;amp;  22 &amp;amp; \cd \\
    \hdashline
    17     &amp;amp;  18 &amp;amp;  19  &amp;amp;  20 &amp;amp;  21 &amp;amp; \cd \\
    \vd    &amp;amp; \vd &amp;amp; \vd  &amp;amp; \vd &amp;amp; \vd &amp;amp; \dd
  \end{array}
  &lt;figcaption&gt;
    The spiral touches the left edge on the \( 4 \)th row where the
    number is \( 4^2 \)
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  Whenever the spiral touches the left edge at the \( m \)th row
  (where \( m \) is even), the number in the first column of that row
  is \( m^2.  \)  Hence, we conclude that \( f(m, 1) = m^2 \) when \( m
  \) is even.  Immediately after touching the left edge, the spiral
  turns downwards into the first column of the next row.  Thus, in the
  next row, i.e. in the \( (m + 1) \)th row, we have \( f(m + 1, 1) =
  m^2 + 1, \) where \( m + 1 \) is odd.  This can be restated as \(
  f(m, 1) = (m - 1)^2 + 1 \) when \( m \) is odd.  Since \( f(1, 1) =
  1, \) we can summarise the two formulas we have found here as:

  \[
    f(m, 1) =
      \begin{cases}
        m^2           &amp;amp; \text{if } m \equiv 0 \pmod{2}, \\
        (m - 1)^2 + 1 &amp;amp; \text{if } m \equiv 1 \pmod{2}.
      \end{cases}
  \]
&lt;/p&gt;
&lt;p&gt;
  We can perform a similar analysis for the numbers at the top edge
  and note that whenever the spiral touches the top edge at the
  \( n \)th column (where \( n \) is odd), the number in the first row
  of that column is \( n^2.  \)  This is illustrated below.
&lt;/p&gt;
&lt;figure&gt;
  \begin{array}{rrr:rrl}
     1 &amp;amp;   2 &amp;amp; \hl 9 &amp;amp;  10 &amp;amp;  25 &amp;amp; \cd \\
     4 &amp;amp;   3 &amp;amp;     8 &amp;amp;  11 &amp;amp;  24 &amp;amp; \cd \\
     5 &amp;amp;   6 &amp;amp;     7 &amp;amp;  12 &amp;amp;  23 &amp;amp; \cd \\
    \hdashline
    16 &amp;amp;  15 &amp;amp;    14 &amp;amp;  13 &amp;amp;  22 &amp;amp; \cd \\
    17 &amp;amp;  18 &amp;amp;    19 &amp;amp;  20 &amp;amp;  21 &amp;amp; \cd \\
    \vd &amp;amp; \vd &amp;amp;  \vd &amp;amp; \vd &amp;amp; \vd &amp;amp; \dd
  \end{array}
  &lt;figcaption&gt;
    The spiral touches the top edge on the \( 3 \)rd column where the
    number is \( 3^2 \)
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  Immediately after touching the top edge, the spiral turns right into
  the next column.  These observations give us the following formula
  for the numbers at the top edge:

  \[
    f(1, n) =
      \begin{cases}
        n^2           &amp;amp; \text{if } n \equiv 1 \pmod{2}, \\
        (n - 1)^2 + 1 &amp;amp; \text{if } n \equiv 0 \pmod{2}.
      \end{cases}
  \]

  Next we will find a formula for any arbitrary number anywhere in the
  grid.
&lt;/p&gt;
&lt;h3 id=&quot;computing-all-grid-numbers-1&quot;&gt;Computing All Grid Numbers&lt;/h3&gt;
&lt;p&gt;
 Since the spiral touches the left edge on even-numbered rows, then
 turns downwards into the next (odd-numbered) row and then starts
 moving right until the diagonal (where it changes direction again),
 the following two rules hold:
&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
    On every odd-numbered row, as we go from left to right, the
    numbers increase until we reach the diagonal.
  &lt;/li&gt;
  &lt;li&gt;
    On every even-numbered row, as we go from left to right, the
    numbers decrease until we reach the diagonal.
  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
  Note that all the numbers we considered in the above two points lie
  on or below the diagonal (or equivalently, on or to the left of the
  diagonal).  Therefore, on an odd-numbered row, we can find the
  numbers on or below the diagonal using the formula \( f(m, n) = f(m,
  1) + (n - 1), \) where \( m \) is odd.  Similarly, on even-numbered
  rows, we can find the numbers on or below the diagonal using the
  formula \( f(m, n) = f(m, 1) - (n - 1), \) where \( m \) is even.
&lt;/p&gt;
&lt;p&gt;
  By a similar analysis, the following rules hold when we consider the
  numbers in a column:
&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
    On every even-numbered column, as we go from top to bottom, the
    numbers increase until we reach the diagonal.
  &lt;/li&gt;
  &lt;li&gt;
    On every odd-numbered column, as we go from top to bottom, the
    numbers decrease until we reach the diagonal.
  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
  Now the numbers on or above the diagonal can be found using the
  formula \( f(m, n) = f(1, n) - (m - 1) \) when \( n \) is odd and \(
  f(m, n) = f(1, n) + (m - 1), \) when \( n \) is even.
&lt;/p&gt;
&lt;p&gt;
  Can we determine from the values of \( m \) and \( n \) if the
  number \( f(m, n) \) is above the diagonal or below it?  Yes, if \(
  m \le n, \) then \( f(m, n) \) lies on or above the diagonal.
  However, if \( m \ge n, \) then \( f(m, n) \) lies on or below the
  diagonal.
&lt;/p&gt;
&lt;p&gt;
  We now have everything we need to write a general formula for
  finding the numbers anywhere in the grid.  Using the four formulas
  and the two inequalities obtained in this section, we get

  \[
    f(m, n) =
      \begin{cases}
        f(1, n) + (m - 1)
        &amp;amp; \text{if } m \le n \text{ and } n \equiv 0 \pmod{2}, \\
        f(1, n) - (m - 1)
        &amp;amp; \text{if } m \le n \text{ and } n \equiv 1 \pmod{2}, \\
        f(m, 1) - (n - 1)
        &amp;amp; \text{if } m \ge n \text{ and } m \equiv 0 \pmod{2}, \\
        f(m, 1) + (n - 1)
        &amp;amp; \text{if } m \ge n \text{ and } m \equiv 1 \pmod{2}.  \\
      \end{cases}
  \]

  Using the equations for \( f(1, n) \) and \( f(m, 1) \) from the
  previous section, the above formulas can be rewritten as

  \[
    f(m, n) =
      \begin{cases}
        (n - 1)^2 + 1 + (m - 1)
        &amp;amp; \text{if } m \le n \text{ and } n \equiv 0 \pmod{2}, \\
        n^2 - (m - 1)
        &amp;amp; \text{if } m \le n \text{ and } n \equiv 1 \pmod{2}, \\
        m^2 - (n - 1)
        &amp;amp; \text{if } m \ge n \text{ and } m \equiv 0 \pmod{2}, \\
        (m - 1)^2 + 1 + (n - 1)
        &amp;amp; \text{if } m \ge n \text{ and } m \equiv 1 \pmod{2}.  \\
      \end{cases}
  \]

  Simplifying the expressions on the right-hand side, we get

  \[
    f(m, n) =
      \begin{cases}
        (n - 1)^2 + m
        &amp;amp; \text{if } m \le n \text{ and } n \equiv 0 \pmod{2}, \\
        n^2 - m + 1
        &amp;amp; \text{if } m \le n \text{ and } n \equiv 1 \pmod{2}, \\
        m^2 - n + 1
        &amp;amp; \text{if } m \ge n \text{ and } m \equiv 0 \pmod{2}, \\
        (m - 1)^2 + n
        &amp;amp; \text{if } m \ge n \text{ and } m \equiv 1 \pmod{2}.  \\
      \end{cases}
  \]

  This is pretty good.  We now have a piecewise formula that works for
  any position in the grid.  Let us now explore whether we can express
  it as a single closed-form expression.
&lt;/p&gt;
&lt;h3 id=&quot;closed-form-expression-1&quot;&gt;Closed Form Expression&lt;/h3&gt;
&lt;p&gt;
  First, we will rewrite the piecewise formula from the previous
  section in the following form:

  \[
    f(m, n) =
      \begin{cases}
        (n^2 - n + 1) + (m - n)
        &amp;amp; \text{if } m \le n \text{ and } n \equiv 0 \pmod{2}, \\
        (n^2 - n + 1) - (m - n)
        &amp;amp; \text{if } m \le n \text{ and } n \equiv 1 \pmod{2}, \\
        (m^2 - m + 1) + (m - n)
        &amp;amp; \text{if } m \ge n \text{ and } m \equiv 0 \pmod{2}, \\
        (m^2 - m + 1) - (m - n)
        &amp;amp; \text{if } m \ge n \text{ and } m \equiv 1 \pmod{2}.  \\
      \end{cases}
  \]

  This is the same formula, rewritten to reveal common patterns
  between the four expressions on the right-hand side.  In each
  expression, one variable plays the dominant role, occurring several
  times, while the other appears only once.  For example, in the first
  two expressions, \( n \) plays the dominant role whereas \( m \)
  occurs only once.  If we look closely, we realise that it is the
  variable that is greater than or equal to the other that plays the
  dominant role.  Therefore the first and third expressions may be
  written as

  \[
    \left( (\max(m, n))^2 - \max(m, n) + 1 \right) + (m - n).
  \]

  Similarly, the second and fourth expressions may be written as

  \[
    \left( (\max(m, n))^2 - \max(m, n) + 1 \right) - (m - n).
  \]

  We have made some progress towards a closed-form expression.  We
  have collapsed the four expressions in the piecewise formula to just
  two.  The only difference between them lies in the sign of the
  second term: it is positive when the dominant variable is even and
  negative when it is odd.  This observation allows us to unify both
  cases into a single expression:

  \[
    f(m, n) = (\max(m, n))^2 - \max(m, n) + 1 + (-1)^{\max(m, n)} (m - n).
  \]

  Now we have a closed-form expression for \( f(m, n) \) that gives
  the number at any position in the grid.
&lt;/p&gt;
&lt;h2 id=&quot;patterns-on-the-diagonal&quot;&gt;Patterns on the Diagonal&lt;/h2&gt;
&lt;p&gt;
  As mentioned earlier, there is a shorter route to the same
  closed-form expression.  This alternative approach is based on
  analysing the numbers along the diagonal of the grid.  We still need
  to examine the edge numbers, but not all of them as we did in the
  previous section.  Some of the reasoning about edge values will be
  repeated here to ensure this section is self-contained.
&lt;/p&gt;
&lt;h3 id=&quot;computing-diagonal-numbers&quot;&gt;Computing Diagonal Numbers&lt;/h3&gt;
&lt;p&gt;
  A number on the diagonal has the same row number and column number.
  In other words, a diagonal number has the value \( f(n, n) \) for
  some positive integer \( n.  \)  Consider the case when \( n \) is
  even.  In this case, the diagonal number is on a segment of the
  spiral that is moving to the left.  The \( n \times n \) subgrid
  formed by the first \( n \) rows and the first \( n \) columns
  contains exactly \( n^2 \) consecutive numbers.  Since the diagonal
  number is on the last row of this subgrid and the numbers in this
  row increase as we move from right to left, the largest number in
  the subgrid must be on the left edge of this row.  Therefore the
  number at the left edge is \( f(n, 1) = n^2, \) where \( n \) is
  even.  This is illustrated below.
&lt;/p&gt;
&lt;figure&gt;
  \begin{array}{rrrr:rl}
     1     &amp;amp;   2 &amp;amp;   9  &amp;amp;     10 &amp;amp;  25 &amp;amp; \cd \\
     4     &amp;amp;   3 &amp;amp;   8  &amp;amp;     11 &amp;amp;  24 &amp;amp; \cd \\
     5     &amp;amp;   6 &amp;amp;   7  &amp;amp;     12 &amp;amp;  23 &amp;amp; \cd \\
    \hl 16 &amp;amp;  15 &amp;amp;  14  &amp;amp; \hl 13 &amp;amp;  22 &amp;amp; \cd \\
    \hdashline
    17     &amp;amp;  18 &amp;amp;  19  &amp;amp;     20 &amp;amp;  21 &amp;amp; \cd \\
    \vd    &amp;amp; \vd &amp;amp; \vd  &amp;amp;    \vd &amp;amp; \vd &amp;amp; \dd
  \end{array}
  &lt;figcaption&gt;
    The spiral touches the left edge on the \( 4 \)th row where the
    number is \( 4^2 \)
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  From the diagonal to the edge of the subgrid, there are \( n \)
  consecutive numbers.  In a sequence of \( n \) consecutive numbers,
  the difference between the maximum number and the minimum number is
  \( n - 1.  \)  Therefore, \( n^2 - f(n, n) = n - 1.  \)  This gives us

  \[
    f(n, n) = n^2 - n + 1 \quad \text{if } n \equiv 0 \pmod{2}.
  \]
&lt;/p&gt;
&lt;p&gt;
  Now consider the case when \( n \) is odd.
&lt;/p&gt;
&lt;figure&gt;
  \begin{array}{rrr:rrl}
     1 &amp;amp;   2 &amp;amp; \hl 9 &amp;amp;  10 &amp;amp;  25 &amp;amp; \cd \\
     4 &amp;amp;   3 &amp;amp;     8 &amp;amp;  11 &amp;amp;  24 &amp;amp; \cd \\
     5 &amp;amp;   6 &amp;amp; \hl 7 &amp;amp;  12 &amp;amp;  23 &amp;amp; \cd \\
    \hdashline
    16 &amp;amp;  15 &amp;amp;    14 &amp;amp;  13 &amp;amp;  22 &amp;amp; \cd \\
    17 &amp;amp;  18 &amp;amp;    19 &amp;amp;  20 &amp;amp;  21 &amp;amp; \cd \\
    \vd &amp;amp; \vd &amp;amp;  \vd &amp;amp; \vd &amp;amp; \vd &amp;amp; \dd
  \end{array}
  &lt;figcaption&gt;
    The spiral touches the top edge on the \( 3 \)rd column where the
    number is \( 3^2 \)
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  By a similar reasoning, for odd \( n, \) the \( n \)th column has
  numbers that increase as we move up from the diagonal number towards
  the top edge.  Therefore \( f(1, n) = n^2 \) and since \( n^2 - f(n,
  n) = n - 1, \) we again obtain

  \[
    f(n, n) = n^2 - n + 1 \quad \text{if } n \equiv 1 \pmod{2}.
  \]

  Since \( f(n, n) \) takes the same form for both odd and even
  \( n, \) we can write

  \[
    f(n, n) = n^2 - n + 1
  \]

  for all positive integers \( n.  \)
&lt;/p&gt;
&lt;h3 id=&quot;computing-all-grid-numbers-2&quot;&gt;Computing All Grid Numbers&lt;/h3&gt;
&lt;p&gt;
  If \( m \le n, \) then the number \( f(m, n) \) lies on or above the
  diagonal number \( f(n, n).  \)  If \( n \) is even, then the numbers
  decrease as we go from the diagonal up to the top edge.  Therefore
  \( f(m, n) \le f(n, n) \) and \( f(m, n) = f(n, n) - (n - m).  \)  If
  \( n \) is odd, then the numbers increase as we go from the diagonal
  up to the top edge and therefore \( f(m, n) \ge f(n, n) \) and \(
  f(m, n) = f(n, n) + (n - m).  \)
&lt;/p&gt;
&lt;p&gt;
  If \( m \ge n, \) then the number \( f(m, n) \) lies on or below the
  diagonal number \( f(m, m).  \)  By a similar analysis, we find that
  \( f(m, n) = f(m, m) + (m - n) \) if \( n \) is even and \( f(m, n)
  = f(m, m) - (m - n) \) if \( n \) is odd.  We summarise these
  results as follows:

  \[
    f(m, n) =
      \begin{cases}
        f(n, n) - (n - m)
        &amp;amp; \text{if } m \le n \text{ and } n \equiv 0 \pmod{2}, \\
        f(n, n) + (n - m)
        &amp;amp; \text{if } m \le n \text{ and } n \equiv 1 \pmod{2}, \\
        f(m, m) + (m - n)
        &amp;amp; \text{if } m \ge n \text{ and } m \equiv 0 \pmod{2}, \\
        f(m, m) - (m - n)
        &amp;amp; \text{if } m \ge n \text{ and } m \equiv 1 \pmod{2}.  \\
      \end{cases}
  \]

  Note that the above formula can be rewritten as

  \[
    f(m, n) =
      \begin{cases}
        f(n, n) + (m - n)
        &amp;amp; \text{if } m \le n \text{ and } n \equiv 0 \pmod{2}, \\
        f(n, n) - (m - n)
        &amp;amp; \text{if } m \le n \text{ and } n \equiv 1 \pmod{2}, \\
        f(m, m) + (m - n)
        &amp;amp; \text{if } m \ge n \text{ and } m \equiv 0 \pmod{2}, \\
        f(m, m) - (m - n)
        &amp;amp; \text{if } m \ge n \text{ and } m \equiv 1 \pmod{2}.  \\
      \end{cases}
  \]
&lt;/p&gt;
&lt;h3 id=&quot;closed-form-expression-2&quot;&gt;Closed Form Expression&lt;/h3&gt;
&lt;p&gt;
  If we take a close look at the last formula in the previous section,
  we find that in each expression, one variable plays a dominant role,
  i.e. it occurs more frequently in the expression than the other.  In
  the first two expressions \( n \) plays the dominant role whereas in
  the last two expressions \( m \) plays the dominant role.  In fact,
  in each expression, the dominant variable is the one that is greater
  than or equal to the other.  With this in mind, we can rewrite the
  above formula as

  \[
    f(m, n) =
      \begin{cases}
        f(\max(m, n), \max(m, n)) + (m - n)
        &amp;amp; \text{if } \max(m, n) \equiv 0 \pmod{2}, \\
        f(\max(m, n), \max(m, n)) - (m - n)
        &amp;amp; \text{if } \max(m, n) \equiv 1 \pmod{2}.  \\
      \end{cases}
  \]

  The only difference between the expressions is the sign of the
  second term: it is positive when \( \max(m, n) \) is even and
  negative when \( \max(m, n) \) is odd.  As a result, we can rewrite
  the above formula as a single expression like this:

  \[
    f(m, n) = f(\max(m, n), \max(m, n)) + (-1)^{\max(m, n)} (m - n).
  \]

  Using the formula \( f(n, n) = n^2 - n + 1 \) from the previous
  section, we get

  \[
    f(m, n) = (\max(m, n))^2 - \max(m, n) + 1 + (-1)^{\max(m, n)} (m - n).
  \]

  We arrive again at the same closed-form expression, this time by
  focusing on the diagonal of the grid.
&lt;/p&gt;
&lt;h2 id=&quot;references&quot;&gt;References&lt;/h2&gt;
&lt;ul&gt;
  &lt;li&gt;
    &lt;a href=&quot;https://cses.fi/problemset/task/1071&quot;&gt;Number Spiral&lt;/a&gt;
    from the CSES Problem Set
  &lt;/li&gt;
  &lt;li&gt;
    &lt;a href=&quot;https://mathworld.wolfram.com/Closed-FormSolution.html&quot;&gt;Closed-Form Solution&lt;/a&gt;
    by Christopher Stover and Eric W. Weisstein
  &lt;/li&gt;
  &lt;li&gt;
    &lt;a href=&quot;https://mathworld.wolfram.com/PiecewiseFunction.html&quot;&gt;Piecewise Function&lt;/a&gt;
    by Eric W. Weisstein
  &lt;/li&gt;
&lt;/ul&gt;
<!-- ### -->
&lt;p&gt;
  &lt;a href="https://susam.net/zigzag-number-spiral.html"&gt;Read on website&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/mathematics.html&quot;&gt;#mathematics&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/puzzle.html&quot;&gt;#puzzle&lt;/a&gt;
&lt;/p&gt;
<!-- END HTML -->
    </content>
  </entry>
  <entry>
    <title>Wordle With Grep</title>
    <link href="https://susam.net/wordle-with-grep.html"/>
    <id>urn:uuid:5e705240-72ed-4ef8-86a1-bf3a99f50d50</id>
    <updated>2022-01-22T00:00:00Z</updated>
    <content type="html">
<!-- BEGIN HTML -->
&lt;p&gt;
  Let us solve a couple of
  &lt;a href=&quot;https://www.powerlanguage.co.uk/wordle/&quot;&gt;Wordle&lt;/a&gt; games
  with the Unix &lt;code&gt;grep&lt;/code&gt; command and the
  Unix &lt;code&gt;words&lt;/code&gt; file.  The Wordle games #217, #218 and #219
  for 22&amp;nbsp;Jan&amp;nbsp;2022, 23&amp;nbsp;Jan&amp;nbsp;2022 and
  24&amp;nbsp;Jan&amp;nbsp;22 respectively are used as examples in this post.
  The output examples shown below are obtained using the words
  file &lt;code&gt;/usr/share/dict/words&lt;/code&gt;, GNU grep 3.6 and GNU bash
  5.1.4 on Debian GNU/Linux 11.2 (bullseye).
&lt;/p&gt;
&lt;p&gt;
  Note that the original Wordle game uses a different word list.
  Further, there are several Wordle clones which may have their own
  word lists.  For the purpose of this post, we will use the word list
  that comes with Debian.  We will solve each Wordle in a quick and
  dirty manner in this post.  The focus is going to be on making
  constant progress and reaching the solution quickly with simple
  shell commands.
&lt;/p&gt;
&lt;h2 id=&quot;contents&quot;&gt;Contents&lt;/h2&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;#preliminary-work&quot;&gt;Preliminary Work&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#wordle-217&quot;&gt;Wordle #217&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#wordle-218&quot;&gt;Wordle #218&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#wordle-219&quot;&gt;Wordle #219&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;preliminary-work&quot;&gt;Preliminary Work&lt;/h2&gt;
&lt;p&gt;
  Before we start solving Wordle games, we will do some preliminary
  work.  We will create a convenient shell alias that automatically
  selects all five-letter words from the &lt;code&gt;words&lt;/code&gt; files.  We
  will also find a good word to enter as the first guess into the
  Wordle game.  The following steps elaborate this preliminary work:
&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;
      Make a shell alias named &lt;code&gt;words&lt;/code&gt; that selects all 5
      letter words from the words file.
    &lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;$ &lt;kbd&gt;alias words=&apos;grep &quot;^[a-z]\{5\}$&quot; /usr/share/dict/words&apos;&lt;/kbd&gt;
$ &lt;kbd&gt;words | head -n 3&lt;/kbd&gt;
abaci
aback
abaft
$ &lt;kbd&gt;words | tail -n 3&lt;/kbd&gt;
zoned
zones
zooms
$ &lt;kbd&gt;words | wc -l&lt;/kbd&gt;
4594&lt;/samp&gt;&lt;/pre&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;
      For each letter in the English alphabet, count the number of
      five-letter words that contain the letter.  Rank each letter by
      this count.
    &lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;$ &lt;kbd&gt;for c in {a..z}; do echo $(words | grep $c | wc -l) $c; done | sort -rn | head -n 15&lt;/kbd&gt;
2245 s
2149 e
1736 a
1404 r
1301 o
1231 i
1177 l
1171 t
975 n
924 d
810 u
757 c
708 p
633 h
623 y&lt;/samp&gt;&lt;/pre&gt;
    &lt;p&gt;
      The output shows that the letter &apos;s&apos; occurs in 2245 five-letter
      words, followed by &apos;e&apos; which occurs in 2149 five-letter words
      and so on.
    &lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;
      Find a word that contains the top five letters found in the
      previous step.
    &lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;$ &lt;kbd&gt;words | grep s | grep e | grep a | grep r | grep o&lt;/kbd&gt;
arose&lt;/samp&gt;&lt;/pre&gt;
    &lt;p&gt;
      We will enter this word as the first guess in every Wordle game.
    &lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;
      In case, the word &quot;arose&quot; does not lead to any positive result,
      we will need another word to enter as our second guess.  Find a
      word that contains the next five top letters in the list found
      above.
    &lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;$ &lt;kbd&gt;words | grep i | grep l | grep t | grep n | grep d&lt;/kbd&gt;
$ &lt;kbd&gt;words | grep i | grep l | grep t | grep n | grep u&lt;/kbd&gt;
until&lt;/samp&gt;&lt;/pre&gt;
    &lt;p&gt;
      We found that there is no such word that contains &apos;i&apos;, &apos;l&apos;, &apos;t&apos;,
      &apos;n&apos; and &apos;d&apos;.  So we got rid of &apos;d&apos; in our search and included
      &apos;u&apos; (the next highest ranking letter after &apos;d&apos;) instead to find
      the word &quot;until&quot;.  We will enter this word as the second guess
      if and only if the first guess (i.e. &quot;arose&quot;) does not lead to
      any positive result.
    &lt;/p&gt;
&lt;/ol&gt;
&lt;h2 id=&quot;wordle-217&quot;&gt;Wordle #217&lt;/h2&gt;
&lt;p&gt;
  Let us now solve Wordle #217 for Sat,&amp;nbsp;22&amp;nbsp;Jan&amp;nbsp;2022
  with the following steps:
&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;
      Use the word &quot;arose&quot; as the first guess.  The following result
      appears:
    &lt;/p&gt;
    &lt;p style=&quot;font-family: monospace; font-weight: bold; color: #ddd&quot;&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;A&lt;/span&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;R&lt;/span&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;O&lt;/span&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;S&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;E&lt;/span&gt;
    &lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;
      The previous result shows that the letter &apos;e&apos; occurs at the
      fifth place.  Further, the letters &apos;a&apos;, &apos;r&apos;, &apos;o&apos; and &apos;s&apos; do not
      occur anywhere in the word.  Look for words satisfying these
      constraints.
    &lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;$ &lt;kbd&gt;words | grep &apos;....e&apos; | grep -v &apos;[aros]&apos; | head -n 5&lt;/kbd&gt;
beige
belie
belle
bible
bilge&lt;/samp&gt;&lt;/pre&gt;
    &lt;p&gt;
      Pick the word &quot;beige&quot; for the second guess and enter it into the
      Wordle game.  Note that since we are following a quick and dirty
      approach here, we do not spend any time figuring out which of
      the various five-letter words ending with the letter &apos;e&apos; is the
      most optimal choice for the next guess.  We simply pick the
      first word from the output above and enter it as the second
      guess.  The following result appears now:
    &lt;/p&gt;
    &lt;p style=&quot;font-family: monospace; font-weight: bold; color: #ddd&quot;&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;B&lt;/span&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;E&lt;/span&gt;
      &lt;span style=&quot;background: #b93; padding: 0.5em&quot;&gt;I&lt;/span&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;G&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;E&lt;/span&gt;
    &lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;
      The letter &apos;i&apos; occurs somewhere in the word but not at the third
      place.  Further the letters &apos;b&apos; and &apos;g&apos; do not occur anywhere in
      the word.  Also, the letter &apos;e&apos; does not occur anywhere apart
      from the fifth place.  The letter &apos;e&apos; in the gray tile in the
      second place confirms that the letter &apos;e&apos; does not repeat in the
      answer word.  Refine the previous command to add these
      constraints.
    &lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;$ &lt;kbd&gt;words | grep &apos;[^e][^e][^ie][^e]e&apos; | grep i | grep -v &apos;[arosbg]&apos; | head -n 5&lt;/kbd&gt;
fiche
indue
lithe
mince
niche&lt;/samp&gt;&lt;/pre&gt;
    &lt;p&gt;
      Enter &quot;fiche&quot; as the third guess.  The following result appears:
    &lt;/p&gt;
    &lt;p style=&quot;font-family: monospace; font-weight: bold; color: #ddd&quot;&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;F&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;I&lt;/span&gt;
      &lt;span style=&quot;background: #b93; padding: 0.5em&quot;&gt;C&lt;/span&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;H&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;E&lt;/span&gt;
    &lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;
      The previous result shows that the letter &apos;i&apos; occurs at the
      second place.  Further, the letter &apos;c&apos; occurs somewhere in the
      word but not at the third place.  Also, the letters &apos;f&apos; and &apos;h&apos;
      do not occur anywhere in the word.  Refine the previous command
      further to add these constraints:
    &lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;$ &lt;kbd&gt;words | grep &apos;[^e]i[^iec][^e]e&apos; | grep c | grep -v &apos;[arosbgfh]&apos; | head -n 5&lt;/kbd&gt;
mince
wince&lt;/samp&gt;&lt;/pre&gt;
    &lt;p&gt;
      Enter the word &quot;mince&quot; for the fourth guess.  It leads to the
      following result:
    &lt;/p&gt;
    &lt;p style=&quot;font-family: monospace; font-weight: bold; color: #ddd&quot;&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;M&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;I&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;N&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;C&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;E&lt;/span&gt;
    &lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;
      We are almost there!  We now have all the letters except the
      first one.  The previous result shows that the letter &apos;m&apos; does
      not occur in the word.  Thus the answer word must be &quot;wince&quot;.
      For the sake of completeness, here is a refined search that
      selects the answer word based on the constraints known so far:
    &lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;$ &lt;kbd&gt;words | grep &apos;[^e]ince&apos; | grep -v &apos;[arosbgfhm]&apos; | head -n 5&lt;/kbd&gt;
wince&lt;/samp&gt;&lt;/pre&gt;
    &lt;p&gt;
      It looks like we have found the answer word.  Enter &quot;wince&quot; as
      the fifth guess to get the following result:
    &lt;/p&gt;
    &lt;p style=&quot;font-family: monospace; font-weight: bold; color: #ddd&quot;&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;W&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;I&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;N&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;C&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;E&lt;/span&gt;
    &lt;/p&gt;
    &lt;p&gt;
      Done!
    &lt;/p&gt;
&lt;/ol&gt;
&lt;h2 id=&quot;wordle-218&quot;&gt;Wordle #218&lt;/h2&gt;
&lt;p&gt;
  Now that the wordle for Sat,&amp;nbsp;22&amp;nbsp;Jan&amp;nbsp;2022 is solved,
  let us try the same method on Wordle #219 for
  Sun,&amp;nbsp;23&amp;nbsp;Jan&amp;nbsp;2022 and see how well this method works.
  Here are the steps:
&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;
      Like before, the first guess is &quot;arose&quot;.  Entering this word
      leads to the following result:
    &lt;/p&gt;
    &lt;p style=&quot;font-family: monospace; font-weight: bold; color: #ddd&quot;&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;A&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;R&lt;/span&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;O&lt;/span&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;S&lt;/span&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;E&lt;/span&gt;
    &lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;
      Now search for words based on the previous result.
    &lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;$ &lt;kbd&gt;words | grep &apos;.r...&apos; | grep -v &apos;[aose]&apos; | head -n 5&lt;/kbd&gt;
brick
bring
brink
briny
bruin&lt;/samp&gt;&lt;/pre&gt;
    &lt;p&gt;
      Enter the word &quot;brick&quot; as the second guess.  This leads to the
      following result:
    &lt;/p&gt;
    &lt;p style=&quot;font-family: monospace; font-weight: bold; color: #ddd&quot;&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;B&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;R&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;I&lt;/span&gt;
      &lt;span style=&quot;background: #b93; padding: 0.5em&quot;&gt;C&lt;/span&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;K&lt;/span&gt;
    &lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;
      Use the previous result to refine the search further.
    &lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;$ &lt;kbd&gt;words | grep &apos;.ri[^c].&apos; | grep c | grep -v &apos;[aosebk]&apos; | head -n 5&lt;/kbd&gt;
crimp&lt;/samp&gt;&lt;/pre&gt;
    &lt;p&gt;
      Enter &quot;crimp&quot; as the third guess.  This leads to the following
      result:
    &lt;/p&gt;
    &lt;p style=&quot;font-family: monospace; font-weight: bold; color: #ddd&quot;&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;C&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;R&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;I&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;M&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;P&lt;/span&gt;
    &lt;/p&gt;
    &lt;p&gt;
      Done!
    &lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id=&quot;wordle-219&quot;&gt;Wordle #219&lt;/h2&gt;
&lt;p&gt;
  Finally, let us solve Wordle #219 for
  Mon,&amp;nbsp;24&amp;nbsp;Jan&amp;nbsp;2022.
&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;
      Enter &quot;arose&quot; as the first guess to get this result:
    &lt;/p&gt;
    &lt;p style=&quot;font-family: monospace; font-weight: bold; color: #ddd&quot;&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;A&lt;/span&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;R&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;O&lt;/span&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;S&lt;/span&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;E&lt;/span&gt;
    &lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;
      The previous result shows that the third letter is &apos;o&apos; and the
      letters &apos;a&apos;, &apos;r&apos;, &apos;s&apos; and &apos;e&apos; do not occur anywhere in the word.
      Search for words that match these constraints.
    &lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;$ &lt;kbd&gt;words | grep &apos;..o..&apos; | grep -v &apos;[arse]&apos; | head -n 5&lt;/kbd&gt;
block
blond
blood
bloom
blown&lt;/samp&gt;&lt;/pre&gt;
    &lt;p&gt;
      Enter &quot;block&quot; as the second guess.  This leads to the following
      result:
    &lt;/p&gt;
    &lt;p style=&quot;font-family: monospace; font-weight: bold; color: #ddd&quot;&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;B&lt;/span&gt;
      &lt;span style=&quot;background: #b93; padding: 0.5em&quot;&gt;L&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;O&lt;/span&gt;
      &lt;span style=&quot;background: #333; padding: 0.5em&quot;&gt;C&lt;/span&gt;
      &lt;span style=&quot;background: #b93; padding: 0.5em&quot;&gt;K&lt;/span&gt;
    &lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;
      The previous result shows that the letter &apos;l&apos; occurs somewhere
      in the word but not at the second place.  Similarly, the letter
      &apos;k&apos; occurs somewhere in the word but not at the fifth place.
      Further, the letters &apos;b&apos; and &apos;c&apos; do not occur anywhere in the
      word.  Search for words that match these constraints.
    &lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;$ &lt;kbd&gt;words | grep &apos;.[^l]o.[^k]&apos; | grep l | grep k | grep -v &apos;[arsebc]&apos; | head -n 5&lt;/kbd&gt;
knoll&lt;/samp&gt;&lt;/pre&gt;
    &lt;p&gt;
      Enter &quot;knoll&quot; as the third guess.  It leads to the following
      result:
    &lt;/p&gt;
    &lt;p style=&quot;font-family: monospace; font-weight: bold; color: #ddd&quot;&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;K&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;N&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;O&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;L&lt;/span&gt;
      &lt;span style=&quot;background: #585; padding: 0.5em&quot;&gt;L&lt;/span&gt;
    &lt;/p&gt;
    &lt;p&gt;
      Done!
    &lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;
<!-- ### -->
&lt;p&gt;
  &lt;a href="https://susam.net/wordle-with-grep.html"&gt;Read on website&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/unix.html&quot;&gt;#unix&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/shell.html&quot;&gt;#shell&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/technology.html&quot;&gt;#technology&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/puzzle.html&quot;&gt;#puzzle&lt;/a&gt;
&lt;/p&gt;
<!-- END HTML -->
    </content>
  </entry>
  <entry>
    <title>Loopy C Puzzle</title>
    <link href="https://susam.net/loopy-c-puzzle.html"/>
    <id>urn:uuid:6d1cb15a-3026-4dbb-9842-aa732c806cc8</id>
    <updated>2011-10-01T00:00:00Z</updated>
    <content type="html">
<!-- BEGIN HTML -->
&lt;h2 id=&quot;integer-underflow&quot;&gt;Integer Underflow&lt;/h2&gt;
&lt;p&gt;
  Let us talk a little bit about integer underflow and undefined
  behaviour in C before we discuss the puzzle I want to share in this
  post.
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;

int main()
{
    int i;
    for (i = 0; i &amp;lt; 6; i--) {
        printf(&quot;.&quot;);
    }
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  This code invokes undefined behaviour.  The value in variable
  &lt;code&gt;i&lt;/code&gt; decrements to &lt;code&gt;INT_MIN&lt;/code&gt; after
  &lt;code&gt;|INT_MIN|&lt;/code&gt; iterations.  In the next iteration, there is a
  negative overflow which is undefined for signed integers in C.  On
  many implementations though, &lt;code&gt;INT_MIN - 1&lt;/code&gt; wraps around
  to &lt;code&gt;INT_MAX&lt;/code&gt;.  Since &lt;code&gt;INT_MAX&lt;/code&gt; is not less than
  &lt;code&gt;6&lt;/code&gt;, the loop terminates.  With such implementations, this
  code prints print &lt;code&gt;|INT_MIN| + 1&lt;/code&gt; dots.  With 32-bit integers,
  that amounts to 2147483649 dots.  Here is one such example output:
&lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;$ &lt;kbd&gt;gcc -std=c89 -Wall -Wextra -pedantic foo.c &amp;amp;&amp;amp; ./a.out | wc -c&lt;/kbd&gt;
2147483649&lt;/samp&gt;&lt;/pre&gt;
&lt;p&gt;
  It is worth noting that the above behaviour is only one of the many
  possible ones.  The code invokes undefined behaviour and the ISO
  standard imposes no requirements on a specific implementation of the
  compiler regarding what the behaviour of such code should be.  For
  example, an implementation could also exploit the undefined
  behaviour to turn the loop into an infinite loop.  In fact, GCC does
  optimise it to an infinite loop if we compile the code with
  the &lt;code&gt;-O2&lt;/code&gt; option.
&lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;&lt;kbd&gt;# This never terminates!&lt;/kbd&gt;
$ &lt;kbd&gt;gcc -O2 -std=c89 -Wall -Wextra -pedantic foo.c &amp;amp;&amp;amp; ./a.out&lt;/kbd&gt;&lt;/samp&gt;&lt;/pre&gt;
&lt;h2 id=&quot;puzzle&quot;&gt;Puzzle&lt;/h2&gt;
&lt;p&gt;
  Let us take a look at the puzzle now.
&lt;/p&gt;
&lt;div class=&quot;highlight&quot;&gt;
&lt;p&gt;
  Add or modify exactly one operator in the following code such that
  it prints exactly 6 dots.
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;for (i = 0; i &amp;lt; 6; i--) {
    printf(&quot;.&quot;);
}&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
  An obvious solution is to change &lt;code&gt;i--&lt;/code&gt;
  to &lt;code&gt;i++&lt;/code&gt;.
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;for (i = 0; i &amp;lt; 6; i++) {
    printf(&quot;.&quot;);
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  There are a few more solutions to this puzzle.  One of the solutions
  is very interesting.  We will discuss the interesting solution in
  detail below.
&lt;/p&gt;
&lt;h2 id=&quot;solutions&quot;&gt;Solutions&lt;/h2&gt;
&lt;p&gt;
  &lt;em&gt;&lt;strong&gt;Update on 02 Oct 2011:&lt;/strong&gt; The puzzle has been
  solved in the &lt;a href=&quot;comments/loopy-c-puzzle.html&quot;&gt;comments&lt;/a&gt;
  section.  We will discuss the solutions now.  If you want to think
  about the problem before you see the solutions, this is a good time
  to pause and think about it.  There are spoilers ahead.&lt;/em&gt;
&lt;/p&gt;
&lt;p&gt;
  Here is a list of some solutions:
&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
    &lt;code&gt;for (i = 0; i &amp;lt; 6; i++)&lt;/code&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;code&gt;for (i = 0; i &amp;lt; 6; ++i)&lt;/code&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;code&gt;for (i = 0; -i &amp;lt; 6; i--)&lt;/code&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;code&gt;for (i = 0; i + 6; i--)&lt;/code&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;code&gt;for (i = 0; i ^= 6; i--)&lt;/code&gt;
  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
  The last solution involving the bitwise XOR operation is not
  immediately obvious.  A little analysis is required to understand
  why it works.
&lt;/p&gt;
&lt;h2 id=&quot;generalisation&quot;&gt;Generalisation&lt;/h2&gt;
&lt;p&gt;
  Let us generalise the puzzle by replacing \( 6 \) in the loop with
  an arbitrary positive integer \( n.  \)  The loop in the last
  solution now becomes:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;for (i = 0; i ^= n; i--) {
    printf(&quot;.&quot;);
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  If we denote the value of the variable &lt;code&gt;i&lt;/code&gt; set by the
  execution of &lt;code&gt;i ^= n&lt;/code&gt; after \( k \) dots are printed as
  \( f(k), \) then

  \[
    f(k) =
      \begin{cases}
        0                       &amp;amp; \text{if } k = 0, \\
        n \oplus (f(k - 1) - 1) &amp;amp; \text{if } k \gt 1
      \end{cases}
  \]

  where \( k \) is a nonnegative integer, \( n \) is a positive
  integer and the symbol \( \oplus \) denotes bitwise XOR operation on
  two nonnegative integers.
&lt;/p&gt;
&lt;p&gt;
  Note that \( f(0) \) represents the value of &lt;code&gt;i&lt;/code&gt; set by
  the execution of &lt;code&gt;i ^= n&lt;/code&gt; when no dots have been printed
  yet.
&lt;/p&gt;
&lt;p&gt;
  If we can show that \( n \) is the least value of \( k \) for which
  \( f(k) = 0, \) it would prove that the loop terminates after
  printing \( n \) dots.
&lt;/p&gt;
&lt;p&gt;
  We will see in the next section that for odd values of \( n, \)

  \[
    f(k) =
      \begin{cases}
        n &amp;amp; \text{if } k \text{ is even}, \\
        1 &amp;amp; \text{if } k \text{ is odd}.
      \end{cases}
  \]

  Therefore there is no value of \( k \) for which \( f(k) = 0 \) when
  \( n \) is odd.  As a result, the loop never terminates when \( n \)
  is odd.
&lt;/p&gt;
&lt;p&gt;
  We will then see that for even values of \( n \) and \( 0 \leq k
  \leq n, \)

  \[
    f(k) = 0 \iff k = n.
  \]

  Therefore the loop terminates after printing \( n \) dots when
  \( n \) is even.
&lt;/p&gt;
&lt;h2 id=&quot;lemmas&quot;&gt;Lemmas&lt;/h2&gt;
&lt;p&gt;
  We will first prove a few lemmas about some interesting properties
  of the bitwise XOR operation.  We will then use it to prove the
  claims made in the previous section.
&lt;/p&gt;
&lt;!-- Lemma 1 --&gt;
&lt;p&gt;
&lt;strong&gt;Lemma 1.&lt;/strong&gt;
&lt;em&gt;
  For an odd positive integer \( n, \)

  \[
    n \oplus (n - 1) = 1
  \]

  where the symbol \( \oplus \) denotes bitwise XOR operation on two
  nonnegative integers.
&lt;/em&gt;
&lt;/p&gt;
&lt;p&gt;
  &lt;em&gt;Proof.&lt;/em&gt;  Let the binary representation of \( n \) be \( b_m
  \dots b_1 b_0 \) where \( m \) is a nonnegative integer and
  \( b_m \) represents the most significant nonzero bit of \( n.  \)
  Since \( n \) is an odd number, \( b_0 = 1.  \)

  Thus \( n \) may be written as

  \[
    b_m \dots b_1 1.
  \]

  As a result \( n - 1 \) may be written as

  \[
    b_m \dots b_1 0.
  \]

  The bitwise XOR of both binary representations is \( 1.  \)
&lt;/p&gt;
&lt;!-- Lemma 2 --&gt;
&lt;p&gt;
  &lt;strong&gt;Lemma 2.&lt;/strong&gt;
  &lt;em&gt;
    For a nonnegative integer \( n, \)

    \[
      n \oplus 1 =
      \begin{cases}
      n + 1 &amp;amp; \text{if } n \text{ is even}, \\
      n - 1 &amp;amp; \text{if } n \text{ is odd}.
      \end{cases}
    \]

    where the symbol \( \oplus \) denotes bitwise XOR operation on two
    nonnegative integers.
  &lt;/em&gt;
&lt;/p&gt;
&lt;p&gt;
  &lt;em&gt;Proof.&lt;/em&gt;  Let the binary representation of \( n \) be \( b_m
  \dots b_1 b_0 \) where \( m \) is a nonnegative integer and
  \( b_m \) represents the most significant nonzero bit of \( n.  \)
&lt;/p&gt;
&lt;p&gt;
  If \( n \) is even, \( b_0 = 0.  \)  In this case, \( n \) may be
  written as \( b_m \dots b_1 0.  \)  Thus \( n \oplus 1 \) may be
  written as \( b_m \dots b_1 1.  \)  Therefore \( n \oplus 1 = n + 1.  \)
&lt;/p&gt;
&lt;p&gt;
  If \( n \) is odd, \( b_0 = 1.  \)  In this case, \( n \) may be
  written as \( b_m \dots b_1 1.  \)  Thus \( n \oplus 1 \) may be
  written as \( b_m \dots b_1 0.  \)  Therefore \( n \oplus 1 = n - 1.  \)
&lt;/p&gt;
&lt;p&gt;
  Note that for odd \( n, \) lemma 1 can also be derived as a
  corollary of lemma 2 in this manner:

  \[
    k \oplus (k - 1)
    = k \oplus (k \oplus 1)
    = (k \oplus k) \oplus 1
    = 0 \oplus 1
    = 1.
  \]
&lt;/p&gt;
&lt;!-- Lemma 3 --&gt;
&lt;p&gt;
  &lt;strong&gt;Lemma 3.&lt;/strong&gt;
  &lt;em&gt;
    If \( x \) is an even nonnegative integer and \( y \) is an odd
    positive integer, then \( x \oplus y \) is odd, where the symbol
    \( \oplus \) denotes bitwise XOR operation on two nonnegative
    integers.
  &lt;/em&gt;
&lt;/p&gt;
&lt;p&gt;
  &lt;em&gt;Proof.&lt;/em&gt;  Let the binary representation of \( x \) be \(
  b_{xm_x} \dots b_{x1} b_{x0} \) and that of \( y \) be \( b_{ym_y}
  \dots b_{y1} b_{y0} \) where \( m_x \) and \( m_y \) are nonnegative
  integers and \( b_{xm_x} \) and \( b_{xm_y} \) represent the most
  significant nonzero bits of \( x \) and \( y \) respectively.
&lt;/p&gt;
&lt;p&gt;
  Since \( x \) is even, \( b_{x0} = 0.  \)  Since \( y \) is odd, \(
  b_{y0} = 1.  \)
&lt;/p&gt;
&lt;p&gt;
  Let \( z = x \oplus y \) with a binary representation of \( b_{zm_z}
  \dots b_{z1} b_{z0} \) where \( m_{zm_z} \) is a nonnegative integer
  and \( b_{zm_z} \) is the most significant nonzero bit of \( z.  \)
&lt;/p&gt;
&lt;p&gt;
  We get \( b_{z0} = b_{x0} \oplus b_{y0} = 0 \oplus 1 = 1.  \)
  Therefore \( z \) is odd.
&lt;/p&gt;
&lt;h2 id=&quot;theorems&quot;&gt;Theorems&lt;/h2&gt;
&lt;!-- Theorem 1 --&gt;
&lt;p&gt;
&lt;strong&gt;Theorem 1.&lt;/strong&gt;
&lt;em&gt;
  Let \( \oplus \) denote bitwise XOR operation on two nonnegative
  integers and

  \[
    f(k) =
    \begin{cases}
    n                        &amp;amp; \text{if } n = 0, \\
    n \oplus (f(n - 1) - 1)  &amp;amp; \text{if } n \gt 1.
    \end{cases}
  \]

  where \( k \) is a nonnegative integer and \( n \) is an odd
  positive integer.  Then

  \[
    f(k) =
    \begin{cases}
    n &amp;amp; \text{if } k \text{ is even}, \\
    1 &amp;amp; \text{if } k \text{ is odd}.
    \end{cases}
  \]
&lt;/em&gt;
&lt;/p&gt;
&lt;p&gt;
  &lt;em&gt;Proof.&lt;/em&gt;  This is a proof by mathematical induction.  We have
  \( f(0) = n \) by definition.  Therefore the base case holds good.
&lt;/p&gt;
&lt;p&gt;
  Let us assume that \( f(k) = n \) for any even \( k \) (induction
  hypothesis).  Let \( k&apos; = k + 1 \) and \( k&apos;&apos; = k + 2.  \)
&lt;/p&gt;
&lt;p&gt;
  If \( k \) is even, we get

  \begin{align*}
    f(k&apos;)  &amp;amp; = n \oplus (f(k) - 1)  &amp;amp;&amp;amp; \text{(by definition)} \\
           &amp;amp; = n \oplus (n - 1)     &amp;amp;&amp;amp; \text{(by induction hypothesis)} \\
           &amp;amp; = 1                    &amp;amp;&amp;amp; \text{(by lemma 1)},\\
    f(k&apos;&apos;) &amp;amp; = n \oplus (f(k&apos;) - 1) &amp;amp;&amp;amp; \text{(by definition)} \\
           &amp;amp; = n \oplus (1 - 1)     &amp;amp;&amp;amp; \text{(since \( f(k&apos;) = 1 \))} \\
           &amp;amp; = n \oplus 0 \\
           &amp;amp; = n.
  \end{align*}
&lt;/p&gt;
&lt;p&gt;
  Since \( f(k&apos;&apos;) = n \) and \( k&apos;&apos; \) is the next even number after
  \( k, \) the induction step is complete.  The induction step shows
  that for every even \( k, \) \( f(k) = n \) holds good.  It also
  shows that as a result of \( f(k) = n \) for every even \( k, \) we
  get \( f(k&apos;) = 1 \) for every odd \( k&apos;.  \)
&lt;/p&gt;
&lt;!-- Theorem 2 --&gt;
&lt;p&gt;
  &lt;strong&gt;Theorem 2.&lt;/strong&gt;
  &lt;em&gt;
    Let \( \oplus \) denote bitwise XOR operation on two nonnegative
    integers and

    \[
      f(k) =
        \begin{cases}
          n                        &amp;amp; \text{if } n = 0, \\
          n \oplus (f(n - 1) - 1)  &amp;amp; \text{if } n \gt 1.
        \end{cases}
    \]

    where \( k \) is a nonnegative integer, \( n \) is an even
    positive integer and \( 0 \leq k \leq n.  \)  Then

   \[
     f(k) = 0 \iff k = n.
   \]
&lt;/em&gt;
&lt;/p&gt;
&lt;p&gt;
  &lt;em&gt;Proof.&lt;/em&gt;  We will first show by the principle of mathematical
  induction that for even \( k, \) \( f(k) = n - k.  \)  We have \(
  f(0) = n \) by definition, so the base case holds good.  Now let us
  assume that \( f(k) = n - k \) holds good for any even \( k \) where
  \( 0 \leq k \leq n \) (induction hypothesis).
&lt;/p&gt;
&lt;p&gt;
  Since \( n \) is even (by definition) and \( k \) is even (by
  induction hypothesis), \( f(k) = n - k \) is even.  As a result, \(
  f(k) - 1 \) is odd.  By lemma 3, we conclude that \( f(k + 1) = n
  \oplus (f(k) - 1) \) is odd.
&lt;/p&gt;
&lt;p&gt;
  Now we perform the induction step as follows:

  \begin{align*}
    f(k + 2) &amp;amp; = n \oplus (f(k + 1) - 1)
                     &amp;amp;&amp;amp; \text{(by definition)} \\
             &amp;amp; = n \oplus (f(k + 1) \oplus 1)
                     &amp;amp;&amp;amp; \text{(by lemma 2 for odd \( n \))} \\
             &amp;amp; = n \oplus ((n \oplus (f(k) - 1)) \oplus 1)
                     &amp;amp;&amp;amp; \text{(by definition)} \\
             &amp;amp; = (n \oplus n ) \oplus ((f(k) - 1) \oplus 1)
                     &amp;amp;&amp;amp; \text{(by associativity of XOR)} \\
             &amp;amp; = 0 \oplus ((f(k) - 1) \oplus 1) \\
             &amp;amp; = (f(k) - 1) \oplus 1 \\
             &amp;amp; = (f(k) - 1) - 1
                     &amp;amp;&amp;amp; \text{(from lemma 2 for odd \( n \))} \\
             &amp;amp; = f(k) - 2 \\
             &amp;amp; = n - k - 2
                     &amp;amp;&amp;amp; \text{(by induction hypothesis).}
  \end{align*}

  This completes the induction step and proves that \( f(k) = n - k \)
  for even \( k \) where \( 0 \leq k \leq n.  \)
&lt;/p&gt;
&lt;p&gt;
  We have shown above that \( f(k) \) is even for every even \( k \)
  where \( 0 \leq k \leq n \) which results in \( f(k + 1) \) as odd
  for every odd \( k + 1.  \)  This means that \( f(k) \) cannot be \(
  0 \) for any odd \( k.  \)  Therefore \( f(k) = 0 \) is possible only
  even \( k.  \)  Solving \( f(k) = n - k = 0, \) we conclude that \(
  f(k) = 0 \) if and only if \( k = n.  \)
&lt;/p&gt;
<!-- ### -->
&lt;p&gt;
  &lt;a href="https://susam.net/loopy-c-puzzle.html"&gt;Read on website&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/c.html&quot;&gt;#c&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/programming.html&quot;&gt;#programming&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/technology.html&quot;&gt;#technology&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/mathematics.html&quot;&gt;#mathematics&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/puzzle.html&quot;&gt;#puzzle&lt;/a&gt;
&lt;/p&gt;
<!-- END HTML -->
    </content>
  </entry>
  <entry>
    <title>From Tower of Hanoi to Counting Bits</title>
    <link href="https://susam.net/from-tower-of-hanoi-to-counting-bits.html"/>
    <id>urn:uuid:44fb2019-550f-4ba0-92e2-eab91389cb05</id>
    <updated>2011-09-25T00:00:00Z</updated>
    <content type="html">
<!-- BEGIN HTML -->

&lt;h2 id=&quot;tower-of-hanoi&quot;&gt;Tower of Hanoi&lt;/h2&gt;
&lt;p&gt;
  A few weeks ago, I watched
  &lt;a href=&quot;http://www.imdb.com/title/tt1318514/&quot;&gt;Rise of the Planet of
  the Apes&lt;/a&gt;.  The movie showed a genetically engineered chimpanzee
  trying to solve a puzzle involving four discs, initially stacked in
  ascending order of size on one of three pegs.  The chimpanzee was
  supposed to transfer the entire stack to one of the other pegs,
  moving only one disc at a time and never placing a larger disc on a
  smaller one.
&lt;/p&gt;
&lt;p&gt;
  The problem was called the &lt;em&gt;Lucas&apos; Tower&lt;/em&gt; in the movie.  I
  have always known this problem as the &lt;em&gt;Tower of Hanoi&lt;/em&gt;
  puzzle.  The minimum number of moves required to solve the problem
  is \( 2^n - 1 \) where \( n \) is the number of discs.  In the
  movie, the chimpanzee solved the problem in 15 moves, the minimum
  number of moves required when there are 4 discs.
&lt;/p&gt;
&lt;p&gt;
  Referring to the problem as the Lucas&apos; Tower made me wonder why it
  was called so instead of calling it the Tower of Hanoi.  I guessed
  it was probably because the puzzle was invented by the French
  mathematician &amp;Eacute;douard Lucas.  Later when I checked
  the &lt;a href=&quot;https://en.wikipedia.org/wiki/Tower_of_Hanoi&quot;&gt;Wikipedia
  article on this topic&lt;/a&gt;, I realised I was right about this.  In
  fact, the article mentioned that there is another version of this
  problem known as &lt;em&gt;the Tower of Brahma&lt;/em&gt; that involves 64 discs
  made of pure gold and three diamond needles.  According to a legend,
  a group of Brahmin priests are working at the problem and the world
  will end when the last move of the puzzle is completed.  Now, even
  if they make one move every second, it&apos;ll take
  18&amp;#8239;446&amp;#8239;744&amp;#8239;073&amp;#8239;709&amp;#8239;551&amp;#8239;615
  seconds to complete the puzzle.  That&apos;s about 585 billion years.
  The article also had this nice animation of a solution involving
  four discs.
&lt;/p&gt;
&lt;figure&gt;
  &lt;img src=&quot;files/blog/tower-of-hanoi-animation.gif&quot;
       alt=&quot;Animated solution of the Tower of Hanoi puzzle&quot;&gt;
  &lt;figcaption&gt;
    Animated solution of the Tower of Hanoi puzzle created by
    Andr&amp;eacute; Karwath
    (&lt;a
    href=&quot;https://commons.wikimedia.org/wiki/File:Tower_of_Hanoi_4.gif&quot;&gt;original
    source&lt;/a&gt;)
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
  I&apos;ll not discuss the solution of this puzzle in this blog post.
  There are plenty of articles on the web including the Wikpedia
  article that describes why it takes a minimum of \( 2^n - 1 \) moves
  to solve the puzzle when there are \( n \) discs involved.  In this
  post, I&apos;ll talk about an interesting result I discovered while
  playing with this puzzle one afternoon.
&lt;/p&gt;
&lt;h2 id=&quot;binary-numbers&quot;&gt;Binary Numbers&lt;/h2&gt;
&lt;p&gt;
  If we denote the minimum number of moves required to solve the Tower
  of Hanoi puzzle as \( T_n, \) then \( T_n \) when expressed in
  binary is the largest possible \( n \)-bit integer.  For example, \(
  T_4 = 15_{10} = 1111_{2}.  \)  That makes sense because \( T_n = 2^n
  - 1 \) indeed represents the maximum possible \( n \)-bit integer
  where all \( n \) bits are set to \( 1.  \)
&lt;/p&gt;
&lt;p&gt;
  While playing with different values of \( T_n \) for different
  values of \( n, \) I stumbled upon an interesting result which I
  will pose as a problem in a later section below.
&lt;/p&gt;
&lt;h2 id=&quot;assumptions&quot;&gt;Assumptions&lt;/h2&gt;
&lt;p&gt;
  Before proceeding to the problem, let us define the bit-length of an
  integer to eliminate any possibility of ambiguity:
&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
    A positive integer \( x \) is said to be an \( n \)-bit integer if
    and only if the minimum number of bits required to express the
    integer is \( n; \) or equivalently, \( \lfloor \log_2 x \rfloor +
    1 = n.  \)
  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
  We will be dealing with arbitrary precision integers (bignums) in
  the problem, so let us also make a few assumptions:
&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
    Addition or subtraction of an \( m \)-bit integer and an \( n \)-bit
    integer (\( m \le n \)) takes \( O(n) \) time.
  &lt;/li&gt;
  &lt;li&gt;
    Counting the number of \( 1 \)-bits in an \( n \)-bit integer takes
    \( O(n) \) time.
  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
  The definition along with the assumptions lead to the following
  conclusions:
&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
    Adding or subtracting two integers \( a \) and \( b \) takes \(
    O(\log(\max(a, b))) \) time.
  &lt;/li&gt;
  &lt;li&gt;
    Counting the number of \( 1 \)-bits in an integer \( a \) takes
    \( O(\log(a)) \) time.
  &lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;binary-puzzle&quot;&gt;Binary Puzzle&lt;/h2&gt;
&lt;p&gt;
  We will now explore the following puzzle in the remainder of this
  post.
&lt;/p&gt;
&lt;div class=&quot;highlight&quot;&gt;
  &lt;p&gt;
    What is the most efficient way to compute the number of \( 1 \)-bits
    in

    \[
      T_1 + T_2 + \dots + T_n
    \]

    where \( n \) is a positive integer, each \( T_i = 2^i - 1 \) for
    integers \( 1 \le i \le n \) and efficiency is measured in terms of
    time and space complexity?
  &lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
  The naive approach involves adding all the \( n \) integers and
  counting the number of \( 1 \)-bits in the sum.  It takes
  \( O(n^2) \) time to add the \( n \) integers.  The sum is an \( (n
  + 1) \)-bit integer, so it takes \( O(n) \) time to count the number
  of \( 1 \)-bits in the sum.  Since the sum is \( (n + 1) \)-bit
  long, it takes \( O(n) \) memory to store the sum.  If \( n \) is as
  large as, say, \( 2^{64}, \) it takes 2 exbibytes plus one more bit
  of memory to store the sum.
&lt;/p&gt;
&lt;p&gt;
  We can arrive at a much more efficient solution if we look at what
  the binary representation of the sum looks like.  We first arrive at
  a closed-form expression for the sum:

  \begin{align*}
    T_1 + T_2 + \dots + T_n
    &amp;amp; = (2 - 1) + (2^2 - 1) + \dots + (2^n - 1) \\
    &amp;amp; = (2 + 2^2 + \dots + 2^n) - n \\
    &amp;amp; = (2^{n + 1} - 2) - n \\
    &amp;amp; = (2^{n + 1} - 1) - (n + 1).
  \end{align*}

  Now \( 2^{n + 1} - 1 \) is an \( (n + 1) \)-bit number with all its
  bits set to \( 1.  \)  Subtracting \( n + 1 \) from it is equivalent
  to performing the following operation with their binary
  representations: for each \( 1 \)-bit in \( (n + 1), \) set the
  corresponding bit in \( (2^{n + 1} - 1) \) to \( 0.  \)
&lt;/p&gt;
&lt;p&gt;
  If we use the notation \( \text{bitcount}(n) \) to represent the
  number of \( 1 \)-bits in the binary representation of a positive
  integer \( n, \) then we get

  \[
    \text{bitcount}(T_1 + T_2 + \dots + T_n)
    = (n + 1) - \text{bitcount}(n + 1).
  \]

  Now the computation involves counting the number of \( 1 \)-bits in
  \( n + 1 \) which takes \( O(\log n) \) and subtracting this count
  from \( n + 1 \) which also takes \( O(\log n) \) time.  Further,
  the largest number that we keep in memory is \( n + 1 \) which
  occupies \( O(\log n) \) space.  Therefore, the entire problem can
  be solved in \( O(\log n) \) time with \( O(\log n) \) space.
&lt;/p&gt;
&lt;p&gt;
  What would have taken 2 exbibytes plus 1 bit of memory with the
  naive approach requires 8 bytes plus 1 bit of memory now.
&lt;/p&gt;
<!-- ### -->
&lt;p&gt;
  &lt;a href="https://susam.net/from-tower-of-hanoi-to-counting-bits.html"&gt;Read on website&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/mathematics.html&quot;&gt;#mathematics&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/puzzle.html&quot;&gt;#puzzle&lt;/a&gt;
&lt;/p&gt;
<!-- END HTML -->
    </content>
  </entry>
  <entry>
    <title>Langford Pairing</title>
    <link href="https://susam.net/langford-pairing.html"/>
    <id>urn:uuid:3b6d1107-fe4c-4a9d-8ce0-ba02423bf622</id>
    <updated>2011-09-17T00:00:00Z</updated>
    <content type="html">
<!-- BEGIN HTML -->
&lt;h2 id=&quot;permutation-problem&quot;&gt;Permutation Problem&lt;/h2&gt;
&lt;p&gt;
  A few days ago, I came across this problem:
&lt;/p&gt;
&lt;div class=&quot;highlight&quot;&gt;
  &lt;p&gt;
    There is a sequence of \( 2n \) numbers where each natural number
    from \( 1 \) to \( n \) is repeated twice, i.e.

    \[
      (1, 1, 2, 2, \dots, n, n).
    \]

    Find a permutation of this sequence such that for each \( k \)
    where \( 1 \le k \le n, \) there are \( k \) numbers between two
    occurrences of \( k \) in the permutation.
  &lt;/p&gt;
&lt;/div&gt;
&lt;h2 id=&quot;getting-started&quot;&gt;Getting Started&lt;/h2&gt;
&lt;p&gt;
  In combinatorics, this problem has a name: &lt;em&gt;Langford&apos;s
  problem&lt;/em&gt;.  A permutation of \( (1, 1, 2, 2, \dots, n, n) \) that
  satisfies the condition given in the probem is known as
  a &lt;em&gt;Langford pairing&lt;/em&gt; or &lt;em&gt;Langford sequence&lt;/em&gt;.
&lt;/p&gt;
&lt;p&gt;
  For small \( n, \) say \( n = 4, \) Langford pairings can be
  obtained easily by trial and error: \( (4, 1, 3, 1, 2, 4, 3, 2).  \)
  What if \( n \) is large?  We need an algorithm to find a
  permutation that solves the problem in that case.
&lt;/p&gt;
&lt;p&gt;
  There is another question to consider: Is there a solution for every
  possible \( n?  \)  One can easily see that there are no Langford
  pairings for \( n = 1 \) and \( n = 2, \) i.e. the sequences \( (1,
  1) \) and \( (1, 1, 2, 2) \) have no Langford pairings.
&lt;/p&gt;
&lt;p&gt;
  We need to understand two things:
&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;
    For what values of \( n \) do Langford pairings exist?
  &lt;/li&gt;
  &lt;li&gt;
    For the values of \( n \) for which Langford pairings exist, how
    do we find the Langford pairings?
  &lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
  A simple Python 3 program I wrote to find Langford pairings for
  small values of \( n \) offers some clues.  Here is the program:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;def find_solutions(n, s=None):
    # If called from top-level (s=None), create a list of 2n zero
    # values.  Zeroes represent unoccupied cells.
    if s is None:
        s = [0] * (2 * n)

    # Next number to be placed.
    m = max(s) + 1

    # For each i, try to place m at s[i] and s[i + m + 1].
    for i in range(2 * n - m - 1):

        # If s[i] and s[i + m + 1] are unoccupied, ...
        if s[i] == s[i + m + 1] == 0:

            # first place m at s[i] and s[i + m + 1].
            s[i] = s[i + m + 1] = m

            # If m is the last number to be placed, ...
            if m == n:
                # then a solution has been found; yield it.
                yield s[:]
            else:
                # else try to place the next number.
                yield from find_solutions(n, s)

            # Undo placement of m.
            s[i] = s[i + m + 1] = 0


# Count solutions for 1 &amp;lt;= n &amp;lt;= 12.
for n in range(1, 13):
    count = sum(1 for s in find_solutions(n))
    print(&apos;n = {:2} =&amp;gt; {:6} solutions&apos;.format(n, count))&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  It takes a few minutes for this program to run.  Here is the output
  of this program:
&lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;$ &lt;kbd&gt;python3 langford.py&lt;/kbd&gt;
n =  1 =&amp;gt;      0 solutions
n =  2 =&amp;gt;      0 solutions
n =  3 =&amp;gt;      2 solutions
n =  4 =&amp;gt;      2 solutions
n =  5 =&amp;gt;      0 solutions
n =  6 =&amp;gt;      0 solutions
n =  7 =&amp;gt;     52 solutions
n =  8 =&amp;gt;    300 solutions
n =  9 =&amp;gt;      0 solutions
n = 10 =&amp;gt;      0 solutions
n = 11 =&amp;gt;  35584 solutions
n = 12 =&amp;gt; 216288 solutions&lt;/samp&gt;&lt;/pre&gt;
&lt;p&gt;
  Note that we always talk about Langford pairings in plural in this
  post.  That&apos;s because either a sequence has no Langford pairings or
  it has two or more Langford pairings.  There is never a sequence
  that has only one Langford pairing.  That&apos;s because if we find at
  least one Langford pairing for a sequence, the reverse of that
  Langford pairing is also a Langford pairing.  Therefore, when
  Langford pairings exist for a sequence, they must at least be two in
  number.  Since they occur in pairs, they are always even in number.
  This is why we don&apos;t have to write &quot;one or more Langford pairings&quot;
  in this post.  We can always write &quot;Langford pairings&quot; instead.
&lt;/p&gt;
&lt;h2 id=&quot;conjecture&quot;&gt;Conjecture&lt;/h2&gt;
&lt;p&gt;
  From the output above, we can form a conjecture:
&lt;/p&gt;
&lt;div class=&quot;highlight&quot;&gt;
  The sequence \( (1, 1, 2, 2, \dots, n, n) \) has Langford pairings
  if and only if \( n \equiv 0 \pmod{4} \) or
  \( n \equiv 3 \pmod{4}.  \)
&lt;/div&gt;
&lt;p&gt;
  For convenience, let us denote the sequence \( (1, 1, 2, 2, \dots,
  n, n) \) as \( S_n.  \)  We will now prove the above conjecture in two
  parts:
&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;
    We will first show that the condition that either \( n \equiv 0
    \pmod{4} \) or \( n \equiv 3 \pmod{4} \) must hold is a
    &lt;em&gt;necessary&lt;/em&gt; condition for the sequence \( S_n \) to have
    Langford pairings.
  &lt;/li&gt;
  &lt;li&gt;
    We will then show that the condition that either \( n \equiv 0
    \pmod{4} \) or \( n \equiv 3 \pmod{4} \) must hold is a
    &lt;em&gt;sufficient&lt;/em&gt; condition for the sequence \( S_n \) to have
    Langford pairings.
  &lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id=&quot;necessity&quot;&gt;Necessity&lt;/h2&gt;
&lt;p&gt;
  Let \( S_n = (1, 1, 2, 2, \dots, n, n) \) be a sequence such that it
  has Langford pairings.  Let us pick an arbitrary Langford pairing \(
  s \) of \( S_n \) and split this Langford pairing \( s \) into two
  mutually exclusive subsequences \( s_1 \) and \( s_2 \) such that:
&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
    \( s_1 \) contains all numbers in odd numbered positions and
  &lt;/li&gt;
  &lt;li&gt;
    \( s_2 \) contains all numbers in even numbered positions.
  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
  For example, if we pick \( s = (1, 7, 1, 2, 5, 6, 2, 3, 4, 7, 5, 3,
  6, 4) \) which is a Langford pairing of \( S_7, \) we split \( s \)
  into

  \begin{align*}
    s_1 &amp;amp; = (1, 1, 5, 2, 4, 5, 6), \\
    s_2 &amp;amp; = (7, 2, 6, 3, 7, 3, 4).
  \end{align*}
&lt;/p&gt;
&lt;p&gt;
  We can make a few observations:
&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;
    Both occurrences of an even number do not occur in the same
    subsequence.
  &lt;/li&gt;
  &lt;li&gt;
    There are \( \left\lfloor \frac{n}{2} \right\rfloor \) even
    numbers in each subsequence.
  &lt;/li&gt;
  &lt;li&gt;
    Both occurrences of an odd number occur in the same subsequence.
  &lt;/li&gt;
  &lt;li&gt;
    There are \( \left\lceil \frac{n}{2} \right\rceil \) odd numbers
    in each subsequence.
  &lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
  Do these observations hold good for every Langford pairing of any
  aribrary \( S_n \) for every positive integer value of \( n?  \)
  Yes, they do.  We will now prove them one by one:
&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;
      Let us consider an even number \( k \) from a Langford pairing.
      If the first occurrence of \( k \) lies at the \( i \)th
      position in the pairing, then its second occurrence lies at the
      \( (i + k + 1) \)th position.  Since \( k \) is even, \( i \)
      and \( i + k + 1 \) have different parities, i.e. if \( i \) is
      odd, then \( i + k + 1 \) is even and vice versa.  Therefore, if
      the first occurrence of \( k \) lies at an odd numbered
      position, its second occurrence must lie at an even numbered
      position and vice versa.  Thus one occurrence of \( k \) must
      belong to \( s_1 \) and the other must belong to \( s_2.  \)
      This proves the first observation.
    &lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;
      The number of even numbers between \( 1 \) and \( n, \)
      inclusive, is \( \left\lfloor \frac{n}{2} \right\rfloor.  \)
      Each of these even numbers has been split equally between
      \( s_1 \) and \( s_2.  \)  This proves the second observation.
    &lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;
      Now let us consider an odd number \( k \) from a Langford
      pairing.  If the first occurrence of \( k \) lies at the
      \( i \)th position in the pairing, then its second occurrence lies at
      the \( (i + k + 1) \)th position.  Since \( k \) is odd, \( i \)
      and \( i + k + 1 \) have the same parity.  Therefore, either
      both occurrences of \( k \) belong to \( s_1 \) or both belong
      to \( s_2.  \)  This proves the third observation.
    &lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;
      Each subsequence, \( s_1 \) or \( s_2 \) has \( n \) numbers
      because we split a Langford pairing \( s \) with \( 2n \)
      numbers equally between the two subsequences.  We have shown
      that each subsequence has \( \left\lfloor \frac{n}{2}
      \right\rfloor \) even numbers.  Therefore the number of odd
      numbers in each subsequence is \( n - \left\lfloor \frac{n}{2}
      \right\rfloor = \left\lceil \frac{n}{2} \right\rceil.  \)
    &lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
  From the third observation, we know that the odd numbers always
  occur in pairs in each subsequence because both occurrences of an
  odd number occur together in the same subsequence.  Therefore, the
  number of odd numbers in each subsequence must be even.  Since the
  number of odd numbers in each subsequence is \( \left\lceil
  \frac{n}{2} \right\rceil \) as proven for the fourth observation, we
  conclude that \( \left\lceil \frac{n}{2} \right\rceil \) must be
  even.
&lt;/p&gt;
&lt;p&gt;
  Now let us see what must \( n \) be like so that \( \left\lceil
  \frac{n}{2} \right\rceil \) is even.
&lt;/p&gt;
&lt;p&gt;
  Let us express \( n \) as \( 4q + r \) where \( q \) is a
  nonnegative integer and \( r \in \{0, 1, 2, 3\}.  \)
&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
    If \( n = 4q + 0, \) then\( \left\lceil \frac{n}{2} \right\rceil =
    \left\lceil \frac{4q}{2} \right\rceil = 2q.  \)
  &lt;/li&gt;
  &lt;li&gt;
    If \( n = 4q + 1, \) then\( \left\lceil \frac{n}{2} \right\rceil =
    \left\lceil \frac{4q + 1}{2} \right\rceil = 2q + 1.  \)
  &lt;/li&gt;
  &lt;li&gt;
    If \( n = 4q + 2, \) then\( \left\lceil \frac{n}{2} \right\rceil =
    \left\lceil \frac{4q + 2}{2} \right\rceil = 2q + 1.  \)
  &lt;/li&gt;
  &lt;li&gt;
    If \( n = 4q + 3, \) then\( \left\lceil \frac{n}{2} \right\rceil =
    \left\lceil \frac{4q + 3}{2} \right\rceil = 2q + 2.  \)
  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
  We see that \( \left\lceil \frac{n}{2} \right\rceil \) is even if
  and only if either \( n \equiv 0 \pmod{4} \) or \( n \equiv 3
  \pmod{4} \) holds good.
&lt;/p&gt;
&lt;p&gt;
  We have shown that if a sequence \( S_n \) has Langford pairings,
  then either \( n \equiv 0 \pmod{4} \) or \( n \equiv 3 \pmod{4}.  \)
  This proves the necessity of the condition.
&lt;/p&gt;
&lt;h2 id=&quot;sufficiency&quot;&gt;Sufficiency&lt;/h2&gt;
&lt;p&gt;
  If we can show that we can construct a Langford pairing for \( (1,
  1, 2, 2, \dots, n, n ) \) for both cases, i.e. \( n \equiv 0
  \pmod{4} \) as well as \( n \equiv 3 \pmod{4}, \) then it would
  complete the proof.
&lt;/p&gt;
&lt;h3 id=&quot;notation&quot;&gt;Notation&lt;/h3&gt;
&lt;p&gt;
  Let us define some notation to make it easier to write sequences we
  will use in the construction of a Langford pairing:
&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;
      \( (i \dots j)_{even} \) denotes a sequence of even positive
      integers from \( i \) to \( j, \) exclusive, arranged in
      ascending order.
    &lt;/p&gt;
    &lt;p&gt;
      For example, \( (1 \dots 8)_{even} = (2, 4, 6) \) and \( (1
      \dots 2)_{even} = ().  \)
    &lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;
      \( (i \dots j)_{odd} \) denotes a sequence of odd positive
      integers from \( i \) to \( j, \) exclusive, arranged in
      ascending order.
    &lt;/p&gt;
    &lt;p&gt;
      For example, \( (1 \dots 8)_{odd} = (3, 5, 7) \) and \( (1 \dots
      3)_{odd} = ().  \)
    &lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;
      \( s&apos; \) denotes the reverse of the sequence \( s.  \)
    &lt;/p&gt;
    &lt;p&gt;
      For example, for a sequence \( s = (2, 3, 4, 5), \) we have \(
      s&apos; = (2, 3, 4, 5)&apos; = (5, 4, 3, 2).  \)
    &lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;
      \( s \cdot t \) denotes the concatenation of sequences \( s \)
      and \( t.  \)
    &lt;/p&gt;
    &lt;p&gt;
      For example, for sequences \( s = (1, 2, 3) \) and
      \( t = (4, 5), \) we have \( s \cdot t = (1, 2, 3) \cdot (4, 5)
      = (1, 2, 3, 4, 5).  \)
    &lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
  Let \( x = \left\lceil \frac{n}{4} \right\rceil.  \)  Therefore,

  \[
    x =
    \begin{cases}
      \frac{n}{4}     &amp;amp; \text{if } n \equiv 0 \pmod{4}, \\
      \frac{n + 1}{4} &amp;amp; \text{if } n \equiv 3 \pmod{4}.
    \end{cases}
  \]

  Let us now define the following eight sequences:

  \begin{align*}
    a &amp;amp; = (2x - 1), \\
    b &amp;amp; = (4x - 2), \\
    c &amp;amp; = (4x - 1), \\
    d &amp;amp; = (4x), \\
    p &amp;amp; = (0 \dots a)_{odd}, \\
    q &amp;amp; = (0 \dots a)_{even}, \\
    r &amp;amp; = (a \dots b)_{odd}, \\
    s &amp;amp; = (a \dots b)_{even}.
  \end{align*}

  Now let us construct a Langford pairing for both cases: \( n \equiv
  0 \pmod{4} \) and \( n \equiv 3 \pmod{4}.  \)  We will do this case by
  case.
&lt;/p&gt;
&lt;h3 id=&quot;case-1&quot;&gt;Case \( n \equiv 0 \pmod{4} \)&lt;/h3&gt;
&lt;p&gt;
  If \( n \equiv 0 \pmod{4}, \) we construct a Langford pairing with
  the following concatenation:

  \[
    s&apos; \cdot
    p&apos; \cdot
    b  \cdot
    p  \cdot
    c  \cdot
    s  \cdot
    d  \cdot
    r&apos; \cdot
    q&apos; \cdot
    b  \cdot
    a  \cdot
    q  \cdot
    c  \cdot
    r  \cdot
    a  \cdot
    d.
  \]

  Let us do an example with \( n = 12.  \)
&lt;/p&gt;
&lt;p&gt;
  For \( n = 12, \) we get \( x = \frac{n}{4} = 3.  \)  Therefore,

  \begin{alignat*}{2}
    a &amp;amp; = (2x - 1)           &amp;amp;&amp;amp; = (5), \\
    b &amp;amp; = (4x - 2)           &amp;amp;&amp;amp; = (10), \\
    c &amp;amp; = (4x - 1)           &amp;amp;&amp;amp; = (11), \\
    d &amp;amp; = (4x)               &amp;amp;&amp;amp; = (12), \\
    p &amp;amp; = (0 \dots a)_{odd}  &amp;amp;&amp;amp; = (1, 3), \\
    q &amp;amp; = (0 \dots a)_{even} &amp;amp;&amp;amp; = (2, 4), \\
    r &amp;amp; = (a \dots b)_{odd}  &amp;amp;&amp;amp; = (7, 9), \\
    s &amp;amp; = (a \dots b)_{even} &amp;amp;&amp;amp; = (6, 8).
  \end{alignat*}

  After performing the specified concatenation, we get the following
  Langford pairing:

  \[
    (
      8, 6, 3, 1, 10, 1, 3, 11, 6, 8, 12, 9,
      7, 4, 2, 10, 5, 2, 4, 11, 7, 9, 5, 12
    ).
  \]

  Let us now show that any construction of a sequence as per this
  specified concatenation always leads to a Langford pairing.
&lt;/p&gt;
&lt;p&gt;
  Each sequence \( a, \) \( b, \) \( c \) and \( d \) has one number
  each.  Each sequence \( p, \) \( q, \) \( r \) and \( s \) has \( x
  - 1 \) numbers each.
&lt;/p&gt;
&lt;p&gt;
  The two occurrences of \( a \) have \( q, \) \( c \) and \( r \) in
  between, i.e.

  \[
    (x - 1) + 1 + (x - 1) = 2x - 1 = a
  \]

  numbers in between.  Similarly, we can check that the two
  occurrences of \( b \) have \( b \) numbers in between; likewise for
  \( c \) and \( d.  \)
&lt;/p&gt;
&lt;p&gt;
  The two occurrences of \( 1 \) belong to \( p \) and \( p&apos;.  \)
  Between these two occurrences of \( 1, \) we have only one element
  of \( b.  \)
&lt;/p&gt;
&lt;p&gt;
  We now show that for each \( k \) in \( p, \) there are \( k \)
  numbers in between.  For any \( k \) in \( p, \) there is the
  sequence \( (0..k)&apos;_{odd} \cdot b \cdot (0..k)_{odd} \) in between
  the two occurrences of \( k, \) i.e, there are \( \frac{k - 1}{2} +
  1 + \frac{k - 1}{2} = k \) numbers in between.  Similarly, we can
  check that for each \( k \) in \( q, \) there are \( k \) numbers in
  between.
&lt;/p&gt;
&lt;p&gt;
  Finally, we show that for each \( k \) in \( r, \) there are \( k \)
  numbers in between.  For any \( k \) in \( r, \) there is the
  sequence \( (a..k)&apos;_{odd} \cdot q&apos; \cdot b \cdot a \cdot q \cdot c
  \cdot (a..k)_{odd} \) in between the two occurrences of \( k.  \)
  Note that \( a \) is odd, so the number of integers in this sequence
  is

  \[
    \frac{k - a - 2}{2} + (x - 1) + 1 + 1 + (x - 1) + 1 + \frac{k - a - 2}{2}.
  \]

  Simplifying the above expression and then substituting
  \( a = 2x - 1, \) we get

  \[
    k - a - 2 + 2x + 1 = k.
  \]

  Similarly, we can check that for each \( k \) in \( s, \) there are
  \( k \) numbers in between.
&lt;/p&gt;
&lt;h3 id=&quot;case-2&quot;&gt;Case \( n \equiv 3 \pmod{4} \)&lt;/h3&gt;
&lt;p&gt;
  If \( n \equiv 3 \pmod{4}, \) we construct a Langford pairing with
  the following concatenation:

  \[
    s&apos; \cdot
    p&apos; \cdot
    b  \cdot
    p  \cdot
    c  \cdot
    s  \cdot
    a  \cdot
    r&apos; \cdot
    q&apos; \cdot
    b  \cdot
    a  \cdot
    q  \cdot
    c  \cdot
    r.
  \]

  Note that this concatenation of sequences is almost the same as the
  concatenation in the previous section with the following two
  differences:
&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
    The sequence \( d \) is not used here.
  &lt;/li&gt;
  &lt;li&gt;
    The sequence \( a \) in the end has moved to replace the sequence
    \( d \) in the middle of the concatenation.
  &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
  Let us do an example with \( n = 11.  \)  For \( n = 12, \) we get \(
  x = \frac{n + 1}{4} = 3.  \)  Therefore, the sequences \( a, \) \(
  b, \) \( c, \) \( p, \) \( q, \) \( r \) and \( s \) are same as
  those in the last example in the previous section.  After performing
  the specified concatenation, we get the following Langford pairing:

  \[
    (
      8, 6, 3, 1, 10, 1, 3, 11, 6, 8, 5,
      9, 7, 4, 2, 10, 5, 2, 4, 11, 7, 9
    ).
  \]

  We can verify that for every \( k \) in a Langford pairing
  constructed in this manner, there are \( k \) numbers in between.
  The verification steps are similar to what we did in the previous
  section.
&lt;/p&gt;
<!-- ### -->
&lt;p&gt;
  &lt;a href="https://susam.net/langford-pairing.html"&gt;Read on website&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/mathematics.html&quot;&gt;#mathematics&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/combinatorics.html&quot;&gt;#combinatorics&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/puzzle.html&quot;&gt;#puzzle&lt;/a&gt;
&lt;/p&gt;
<!-- END HTML -->
    </content>
  </entry>
  <entry>
    <title>Magical Chameleons Puzzle</title>
    <link href="https://susam.net/magical-chameleons-puzzle.html"/>
    <id>urn:uuid:ab050147-e02d-4c1a-80c1-01891975b88e</id>
    <updated>2011-06-19T00:00:00Z</updated>
    <content type="html">
<!-- BEGIN HTML -->
&lt;p&gt;
  An island contained chameleons of three different colours: red,
  green and blue.  The chameleons were studied by some biologists and
  they found that when two chameleons of different colours met they
  changed their colours to the third one.  They found that there were
  2000 red chameleons and 3000 green ones on the day they counted
  them.  They didn&apos;t get time to count the number of blue chameleons.
&lt;/p&gt;
&lt;p&gt;
  When the biologists returned to the island two months later they
  found that all chameleons were red in colour.  They were certain
  that no chameleons died because they did not find dead remains of
  any chameleon.  What does it say about the number of blue chameleons
  on the day the biologists counted the number of red and green
  chameleons?
&lt;/p&gt;
&lt;p&gt;
  See the comments page for the solution.
&lt;/p&gt;
<!-- ### -->
&lt;p&gt;
  &lt;a href="https://susam.net/magical-chameleons-puzzle.html"&gt;Read on website&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/mathematics.html&quot;&gt;#mathematics&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/puzzle.html&quot;&gt;#puzzle&lt;/a&gt;
&lt;/p&gt;
<!-- END HTML -->
    </content>
  </entry>
  <entry>
    <title>Calendar Cubes Puzzle</title>
    <link href="https://susam.net/calendar-cubes-puzzle.html"/>
    <id>urn:uuid:0dafd023-1f6c-4312-ad5a-5f5376b79454</id>
    <updated>2011-06-12T00:00:00Z</updated>
    <content type="html">
<!-- BEGIN HTML -->
&lt;p&gt;
  How many different ways are there to assign the ten digits of Arabic
  numerals (0 to 9) to each face of two cubes to ensure that we can
  arrange both cubes on any day such that the front faces of the cubes
  show the current day of the month?
&lt;/p&gt;
&lt;p&gt;
  For example, on February 9 the cubes would be placed side by side
  such that the front face of the cube on the left side shows 0 and
  that of the one on the right side shows 9.
&lt;/p&gt;
&lt;p&gt;
  Two ways of assigning the digits to the faces of the cubes are
  considered different if and only if it is not possible to get one
  assignment from the other by performing one or more of the following
  operrations:
&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;
    Rotating (reorienting) the digits with respect to the faces they
    belong to.
  &lt;/li&gt;
  &lt;li&gt;
    Rotating the cubes.
  &lt;/li&gt;
  &lt;li&gt;
    Swapping the cubes.
  &lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
  See the comments page for the solution.
&lt;/p&gt;

<!-- ### -->
&lt;p&gt;
  &lt;a href="https://susam.net/calendar-cubes-puzzle.html"&gt;Read on website&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/mathematics.html&quot;&gt;#mathematics&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/puzzle.html&quot;&gt;#puzzle&lt;/a&gt;
&lt;/p&gt;
<!-- END HTML -->
    </content>
  </entry>
  <entry>
    <title>URL in C</title>
    <link href="https://susam.net/url-in-c.html"/>
    <id>urn:uuid:065504d2-121e-48fa-bb44-e5480d76421b</id>
    <updated>2011-06-03T00:00:00Z</updated>
    <content type="html">
<!-- BEGIN HTML -->
&lt;p&gt;
  Here is a silly little C puzzle:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;

int main(void)
{
    https://susam.net/
    printf(&quot;hello, world\n&quot;);
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  This code compiles and runs successfully.
&lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;$ &lt;kbd&gt;c99 hello.c &amp;amp;&amp;amp; ./a.out&lt;/kbd&gt;
hello, world&lt;/samp&gt;&lt;/pre&gt;
&lt;p&gt;
  However, the
  &lt;a href=&quot;http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf&quot;&gt;C99
  standard draft&lt;/a&gt; does not mention anywhere that a URL is a valid
  syntactic element in C.  How does this code work then?
&lt;/p&gt;
&lt;p&gt;
  &lt;em&gt;&lt;strong&gt;Update on 04 Jun 2011:&lt;/strong&gt; The puzzle has been
  solved in the &lt;a href=&quot;comments/url-in-c.html&quot;&gt;comments&lt;/a&gt; section.
  If you want to think about the problem before you see the solutions,
  this is a good time to pause and think about it.  There are spoilers
  ahead.&lt;/em&gt;
&lt;/p&gt;
&lt;p&gt;
  The code works fine because &lt;code&gt;https:&lt;/code&gt; is a label and
  &lt;code&gt;//&lt;/code&gt; following it begins a comment.  In case, you are
  wondering if &lt;code&gt;//&lt;/code&gt; is indeed a valid comment in C, yes, it
  is, since C99.  Download the
  &lt;a href=&quot;http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf&quot;&gt;C99
  standard draft&lt;/a&gt;, go to section 6.4.9 (Comments) and read the
  second point which mentions this:
&lt;/p&gt;
&lt;blockquote&gt;
  Except within a character constant, a string literal, or a comment,
  the characters &lt;code&gt;//&lt;/code&gt; introduce a comment that includes all
  multibyte characters up to, but not including, the next new-line
  character.  The contents of such a comment are examined only to
  identify multibyte characters and to find the terminating new-line
  character.
&lt;/blockquote&gt;
<!-- ### -->
&lt;p&gt;
  &lt;a href="https://susam.net/url-in-c.html"&gt;Read on website&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/absurd.html&quot;&gt;#absurd&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/c.html&quot;&gt;#c&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/programming.html&quot;&gt;#programming&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/technology.html&quot;&gt;#technology&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/puzzle.html&quot;&gt;#puzzle&lt;/a&gt;
&lt;/p&gt;
<!-- END HTML -->
    </content>
  </entry>
  <entry>
    <title>Missing Digit Puzzle</title>
    <link href="https://susam.net/missing-digit-puzzle.html"/>
    <id>urn:uuid:474b3fac-6d3c-4194-8b4f-6578732dfcb6</id>
    <updated>2011-05-14T00:00:00Z</updated>
    <content type="html">
<!-- BEGIN HTML -->
&lt;p&gt;
  There is a 10-digit multiple of 234.  9 of its digits in ascending
  order are: 0, 1, 1, 2, 3, 4, 5, 7 and 9.  What is the missing digit?
&lt;/p&gt;
&lt;p&gt;
  See the comments page for the solution.
&lt;/p&gt;
<!-- ### -->
&lt;p&gt;
  &lt;a href="https://susam.net/missing-digit-puzzle.html"&gt;Read on website&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/mathematics.html&quot;&gt;#mathematics&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/puzzle.html&quot;&gt;#puzzle&lt;/a&gt;
&lt;/p&gt;
<!-- END HTML -->
    </content>
  </entry>
  <entry>
    <title>Ternary Operator Puzzle</title>
    <link href="https://susam.net/ternary-operator-puzzle.html"/>
    <id>urn:uuid:b24e1f9a-596c-48b9-b2be-4bba25aca530</id>
    <updated>2011-04-06T00:00:00Z</updated>
    <content type="html">
<!-- BEGIN HTML -->
&lt;p&gt;
  What is the shortest statement you can write in the C or C++
  programming language to express the following statement?
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;a = (a == 0 ? 0 : 1);&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  See the comments page for the solution.
&lt;/p&gt;
<!-- ### -->
&lt;p&gt;
  &lt;a href="https://susam.net/ternary-operator-puzzle.html"&gt;Read on website&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/c.html&quot;&gt;#c&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/programming.html&quot;&gt;#programming&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/technology.html&quot;&gt;#technology&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/puzzle.html&quot;&gt;#puzzle&lt;/a&gt;
&lt;/p&gt;
<!-- END HTML -->
    </content>
  </entry>
  <entry>
    <title>From Out Shuffles to Multiplicative Order</title>
    <link href="https://susam.net/from-out-shuffles-to-multiplicative-order.html"/>
    <id>urn:uuid:81a33643-0b86-4472-93e4-34debbba8ccd</id>
    <updated>2011-03-23T00:00:00Z</updated>
    <content type="html">
<!-- BEGIN HTML -->
&lt;div style=&quot;display: none&quot;&gt;
  \( \gdef\ord{\operatorname{ord}} \)
&lt;/div&gt;
&lt;h2 id=&quot;out-shuffles&quot;&gt;Out Shuffles&lt;/h2&gt;
&lt;p&gt;
  A &lt;em&gt;perfect riffle shuffle&lt;/em&gt; of a deck of cards involves
  splitting the deck into two halves (one in each hand) and then
  alternately dropping one card from each half till all cards have
  fallen.  If the shuffling is done in such a manner that the bottom
  and the top cards remain preserved at their positions, then it is
  an &lt;em&gt;out shuffle&lt;/em&gt;.
&lt;/p&gt;
&lt;h2 id=&quot;problem&quot;&gt;Problem&lt;/h2&gt;
&lt;p&gt;
  Here is a problem that a colleague asked me recently while
  discussing shuffling techniques:
&lt;/p&gt;
&lt;div class=&quot;highlight&quot;&gt;
  How many out shuffles do we need to perform on a deck of 52 cards to
  return the deck to its initial state?
&lt;/div&gt;
&lt;h2 id=&quot;solution&quot;&gt;Solution&lt;/h2&gt;
&lt;p&gt;
  The solution to this problem is rather long, so it has been split
  into three parts below.
&lt;/p&gt;
&lt;h3 id=&quot;part-1&quot;&gt;Part 1: Congruence Relation&lt;/h3&gt;
&lt;p&gt;
  Let us assume that there are \( n \) cards where \( n \) is a
  positive even integer.  Let us denote these cards as \( c_0, c_1,
  \dots, c_{n-1} \) where \( c_0 \) is the card at index \( 0 \) (top
  of the deck), \( c_{n - 1} \) is the card at index \( n - 1 \)
  (bottom of the deck) and \( c_i \) is the card at index \( i \)
  where \( 0 \le i \le n - 1.  \)
&lt;/p&gt;
&lt;p&gt;
  For example, if we have \( 8 \) cards, then the cards are denoted as

  \[
    c_0, c_1, c_2, c_3, c_4, c_5, c_6, c_7.
  \]

  After the first out shuffle, these cards are now in this order:

  \[
    c_0, c_4, c_1, c_5, c_2, c_6, c_3, c_7.
  \]
&lt;/p&gt;
&lt;p&gt;
  From the problem description and the example above, we see that
  after a single out shuffle, a card at index \( i \) moves to index
  \( 2i \bmod (n - 1) \) for \( 0 \le i \lt n - 1 \) and the card at
  index \( n - 1 \) remains at the same place.
&lt;/p&gt;
&lt;p&gt;
  After \( m \) shuffles a card at index \( i \) moves to index \(
  (2^m i) \bmod (n - 1) \) for \( 0 \le i \lt n - 1.  \)  The card at
  index \( n - 1 \) always remains at the same place.
&lt;/p&gt;
&lt;p&gt;
  The solution to the problem then is the smallest positive integer \(
  m \) such that

  \[
    2^m i \equiv i \pmod{n - 1}.
  \]

  for all integers \( i \) that satisfy the inequality \( 0 \le i \lt
  n - 1.  \)
&lt;/p&gt;
&lt;p&gt;
  In modular arithmetic, we know that

  \[
    ac \equiv bc \pmod{n}
    \iff
    a \equiv b \pmod{n / \gcd(c, n)}.
  \]

  where \( a, \) \( b, \) \( c \) and \( n \) are integers.  Therefore

  \[
    2^m i \equiv i \pmod{n - 1}
    \iff
    2^m \equiv 1 \pmod{(n - 1) / \gcd(i, n - 1)}.
  \]

  Let \( F_{ni} = \frac{n - 1}{\gcd(i, n - 1)} \) where \( 0 \le i \lt
  n - 1.  \)  Now the above congruence relation can be written as

  \[
    2^m \equiv 1 \pmod{F_{ni}}.
  \]
&lt;/p&gt;
&lt;h3 id=&quot;part-2&quot;&gt;Part 2: Multiplicative Order&lt;/h3&gt;
&lt;p&gt;
  The smallest positive integer \( m \) that satisfies the above
  congruence relation is known as the multiplicative order of \( 2 \)
  modulo \( F_{ni}.  \)  It is denoted as \( \ord_{F_{ni}}(2).  \)
&lt;/p&gt;
&lt;p&gt;
  In general, given an integer \( a \) and a positive integer \( n \)
  with \( \gcd(a, n) = 1, \) the multiplicative order of \( a \)
  modulo \( n, \) denoted as \( \ord_{n}(a), \) is the smallest
  positive integer \( k \) such that

  \[
    a^k \equiv 1 \pmod{n}.
  \]

  In this problem, \( n \) is even, so \( n - 1 \) is odd as a result
  of which \( F_{ni} \) is also odd.  As a result, \( \gcd(2, F_{ni}) =
  1.  \)  Therefore, the smallest positive integer \( m \) that
  satisfies the congruence relation \( 2^m \equiv 1 \pmod{F_{ni}} \)
  is denoted as \( \ord_{F_{ni}}(2).  \)
&lt;/p&gt;
&lt;p&gt;
  If \( n = 2, \) \( F_{n0} = F_{n1} = 1, \) therefore \( 2^m \equiv 1
  \pmod{F_{ni}} \) for \( 0 \le i \lt n - 1 \) and all positive
  integers \( m.  \)  This proves the trivial observation that when
  there are only two cards \( c_0 \) and \( c_1, \) they remain at
  index \( 0 \) and index \( 1 \) respectively, after any number of
  out shuffles, i.e. their positions do not change with out shuffles.
&lt;/p&gt;
&lt;h4 id=&quot;case-1&quot;&gt;Case \( n \ge 4 \)&lt;/h4&gt;
&lt;p&gt;
  If \( n \ge 4, \) we know that there exists at least one integer
  between \( 1 \) and \( n - 1 \) that is coprime to \( n - 1 \)
  because \( \varphi(n) \ge 2 \) for \( n \ge 4 \) where
  \( \varphi(n) \) represents Euler&apos;s totient of \( n.  \)
&lt;/p&gt;
&lt;h5 id=&quot;subcase-1-1&quot;&gt;Subcase \( i \) is coprime to \( n - 1 \)&lt;/h5&gt;
&lt;p&gt;
  For any arbitrary \( n \ge 4, \) let \( i \) be an integer that is
  coprime to \( n - 1 \) such that \( 1 \lt i \lt n - 1.  \)  Now \(
  \gcd(i, n - 1 ) = 1, \) so \( F_{ni} = \frac{n - 1}{\gcd(i, n - 1)}
  = n - 1.  \)  As a result, \( \ord_{F_{ni}}(2) = \ord_{n -
  1}({2}).  \)  This shows that any card at index \( i \) such that \(
  i \) is coprime to \( n - 1 \) requires a minimum of \( \ord_{n -
  1}(2) \) out shuffles to return to its initial place.
&lt;/p&gt;
&lt;h5 id=&quot;subcase-1-2&quot;&gt;Subcase \( i \) is &lt;em&gt;not&lt;/em&gt; coprime to \( n - 1 \)&lt;/h5&gt;
&lt;p&gt;
  For any arbitrary \( n \ge 4, \) now let us consider the case of a
  card at index \( i \) such that \( i \) is not coprime to
  \( n - 1.  \)  Since \( n - 1 \) is odd, we have \( \gcd(2, n - 1) =
  1.  \)  Therefore, by definition of multiplicative order,

  \[
    2^{\ord_{n - 1}(2)} \equiv 1 \pmod{n - 1}.
  \]

  Since \( F_{ni} \mid n - 1, \) we get,

  \[
    2^{\ord_{n - 1}(2)} \equiv 1 \pmod{F_{ni}}.
  \]

  This shows that a card at index \( i \) such that \( i \) is not
  coprime to \( n - 1 \) also return to its initial place after \(
  \ord_{n - 1}(2) \) out shuffles.  Actually, it takes only \(
  \ord_{F_{ni}}(2) \) out shuffles to return the card to its initial
  place.  But \( \ord_{F_{ni}}(2) \mid \ord_{n - 1}(2), \) so \(
  \ord_{n - 1}(2) = c \ord_{F_{ni}}(2) \) for some positive integer \(
  c.  \)  Therefore performing \( \ord_{n - 1}(2) \) out shuffles is
  same as repeating \( \ord_{F_{ni}}(2) \) out shuffles \( c \) times.
  Every \( \ord_{F_{ni}}(2) \) brings back the card to its initial
  position, so repeating it \( c \) times also brings it back to its
  initial position.
&lt;/p&gt;
&lt;p&gt;
  We have shown that a card at index \( i \) such that \( i \) is
  coprime to \( n - 1 \) takes a minimum of \( \ord_{n - 1}(2) \) out
  shuffles to return to its initial place.  We have also shown that a
  card at other indices also return to its initial place after the
  same number of out shuffles.  Therefore, it takes a minimum of \(
  \ord_{n - 1}{2} \) out shuffles to return the deck of cards to its
  initial state.
&lt;/p&gt;
&lt;h4 id=&quot;case-2&quot;&gt;Case \( n = 2 \)&lt;/h4&gt;
&lt;p&gt;
  When there are only \( 2 \) cards in the deck, every out shuffle
  trivially returns the deck to its initial state.  In other words, it
  takes only \( 1 \) out shuffle to return the deck to its initial
  state.  Indeed \( \ord_{n - 1}(2) = \ord_{1}(2) = 1.  \)
&lt;/p&gt;
&lt;p&gt;
  We have now shown that for any positive even integer \( n, \) a deck
  of \( n \) cards returns to its initial state after \( \ord_{n -
  1}(2) \) out shuffles.
&lt;/p&gt;
&lt;h3 id=&quot;part-3&quot;&gt;Part 3: Computing Multiplicative Order&lt;/h3&gt;
&lt;p&gt;
  For a deck of \( 52 \) cards, we have \( n = 52.  \)  A minimum of \(
  \ord_{51}(2) \) out shuffles are required to return the deck to its
  initial state.  To compute \( \ord_{51}(2) \) we first enumerate the
  powers of \( 2 \) modulo \( 51 \):

  \begin{alignat*}{2}
    2^0 &amp;amp; \equiv 1  &amp;amp;&amp;amp; \pmod{51}, \\
    2^1 &amp;amp; \equiv 2  &amp;amp;&amp;amp; \pmod{51}, \\
    2^2 &amp;amp; \equiv 4  &amp;amp;&amp;amp; \pmod{51}, \\
    2^3 &amp;amp; \equiv 8  &amp;amp;&amp;amp; \pmod{51}, \\
    2^4 &amp;amp; \equiv 16 &amp;amp;&amp;amp; \pmod{51}, \\
    2^5 &amp;amp; \equiv 32 &amp;amp;&amp;amp; \pmod{51}, \\
    2^6 &amp;amp; \equiv 13 &amp;amp;&amp;amp; \pmod{51}, \\
    2^7 &amp;amp; \equiv 26 &amp;amp;&amp;amp; \pmod{51}, \\
    2^8 &amp;amp; \equiv 1  &amp;amp;&amp;amp; \pmod{51}.
  \end{alignat*}

  The smallest positive integer \( k \) such that \( 2^k \equiv 1
  \pmod{51} \) is 8, so \( \ord_51(2) = 8.  \)  We need \( 8 \) out
  shuffles to return a deck of \( 52 \) cards to its initial state.
&lt;/p&gt;
<!-- ### -->
&lt;p&gt;
  &lt;a href="https://susam.net/from-out-shuffles-to-multiplicative-order.html"&gt;Read on website&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/mathematics.html&quot;&gt;#mathematics&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/combinatorics.html&quot;&gt;#combinatorics&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/puzzle.html&quot;&gt;#puzzle&lt;/a&gt;
&lt;/p&gt;
<!-- END HTML -->
    </content>
  </entry>
  <entry>
    <title>Polar Bear Puzzle</title>
    <link href="https://susam.net/polar-bear-puzzle.html"/>
    <id>urn:uuid:0bac78e1-f705-4bae-b62d-5de1fd1dec74</id>
    <updated>2011-03-09T00:00:00Z</updated>
    <content type="html">
<!-- BEGIN HTML -->
&lt;p&gt;
  Alice asked Bob, &quot;A bear walked 1 km south, then 1 km west, then 1
  km north and it was back at the point from where it started.  What
  colour was the bear most likely to be?&quot;
&lt;/p&gt;
&lt;p&gt;
  Bob thought for a while, could not arrive at an answer and gave up.
  Alice explained, &quot;Well, the answer is white.  It is a polar bear.
  It is only when you start from the North Pole that after travelling
  1 km south, 1 km west and 1 km north you would end up at the point
  where you started.&quot;
&lt;/p&gt;
&lt;p&gt;
  Bob replied, &quot;That is an interesting solution.  Now that I
  understand your solution, I realise that there are other starting
  points apart from the North Pole where one could walk 1 km south,
  then 1 km west and then 1 km north to return to the starting point.&quot;
&lt;/p&gt;
&lt;p&gt;
  Can you find all the other such starting points that Bob is talking
  about?
&lt;/p&gt;
&lt;p&gt;
  See the comments page for the solution.
&lt;/p&gt;
<!-- ### -->
&lt;p&gt;
  &lt;a href="https://susam.net/polar-bear-puzzle.html"&gt;Read on website&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/mathematics.html&quot;&gt;#mathematics&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/puzzle.html&quot;&gt;#puzzle&lt;/a&gt;
&lt;/p&gt;
<!-- END HTML -->
    </content>
  </entry>
  <entry>
    <title>Shrinking List Puzzle</title>
    <link href="https://susam.net/shrinking-list-puzzle.html"/>
    <id>urn:uuid:d87a4167-163d-42c4-9589-928674ab9db0</id>
    <updated>2011-02-17T00:00:00Z</updated>
    <content type="html">
<!-- BEGIN HTML -->
&lt;p&gt;
  The first \( 9 \) natural numbers are given in a list.  You are
  supposed to select two numbers randomly from the list, call them \(
  x \) and \( y, \) remove them from the list and insert \( x + y + xy \)
  into the list.  You keep repeating this until you are left with only
  one number in the list.  Find the final number that is left in the
  list.
&lt;/p&gt;
&lt;p&gt;
  See the comments page for the solution.
&lt;/p&gt;
<!-- ### -->
&lt;p&gt;
  &lt;a href="https://susam.net/shrinking-list-puzzle.html"&gt;Read on website&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/mathematics.html&quot;&gt;#mathematics&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/puzzle.html&quot;&gt;#puzzle&lt;/a&gt;
&lt;/p&gt;
<!-- END HTML -->
    </content>
  </entry>
  <entry>
    <title>From Diophantine Equation to Fermat's Last Theorem</title>
    <link href="https://susam.net/from-diophantine-equation-to-fermats-last-theorem.html"/>
    <id>urn:uuid:6fad92a5-62f0-4bf1-aaaa-d5167426db8d</id>
    <updated>2011-01-12T00:00:00Z</updated>
    <content type="html">
<!-- BEGIN HTML -->
&lt;p&gt;
  Here is a puzzle I created recently for my friends who love to
  indulge in recreational mathematics:
&lt;/p&gt;
&lt;div class=&quot;highlight&quot;&gt;
  Find all integer solutions to the equation

  \[
    y^2 + 3 = \frac{x^3}{18}.
  \]
&lt;/div&gt;
&lt;p&gt;
  &lt;em&gt;If you want to think about this puzzle, this is a good time to
  pause and think about it.  There are spoilers ahead.&lt;/em&gt;
&lt;/p&gt;
&lt;p&gt;
  It does not take long to realise that this is a Diophantine equation
  of the form \( a^n + b^n = c^n.  \)  Here is how the equation looks
  after rearranging the terms:

  \[
    x^3 = 18y^2 + 54.
  \]
&lt;/p&gt;
&lt;p&gt;
  The right hand side is positive, so any \( x \) that satisfies this
  equation must also be positive, i.e. \( x \gt 0 \) must hold good
  for any solution \( x \) and \( y.  \)
&lt;/p&gt;
&lt;p&gt;
  Also, if some \( y \) satisfies the equation, then \( -y \) also
  satisfies the equation because the right hand side value remains the
  same for both \( y \) and \( -y.  \)
&lt;/p&gt;
&lt;p&gt;
  The right hand side is \( 2(9y^2 + 3^3).  \)  This is of the form \(
  2(3a^2b + b^3) \) where \( a = y \) and \( b = 3.  \)  Now \( 2(3a^2b
  + b^3) = (a + b)^3 - (a - b)^3.  \)  Using these details, we get

  \[
    x^3 = 18y^2 + 54 = 2(9y^2 + 3^3) = (y + 3)^3 - (y - 3)^3.
  \]

  Rearranging the terms, we get

  \[
    x^3 + (y - 3)^3 = (y + 3)^3.
  \]

  From Fermat&apos;s Last Theorem, we know that an equation of the form \(
  a^n + b^n = c^n \) does not have any solution for positive integers
  \( a, \) \( b, \) \( c \) and positive integer \( n \gt 2.  \)  We
  know that \( x \gt 0.  \)  Therefore \( y \gt 3 \) contradicts
  Fermat&apos;s Last Theorem.  Thus the inequality \( y \le 3 \) must hold
  good.  Further since for every solution \( x \) and \( y, \) there
  is also a solution \( x \) and \( -y, \) the inequality \( -y \le
  3 \) must also hold good.  Therefore values of \( x \) and \( y \)
  that satisfy the above equation must satisfy the following
  inequalities:

  \begin{align*}
    x \gt 0, \\
    -3 \le y \le 3.
  \end{align*}

  Since \( y \) must be one of the seven integers between \( -3 \) and
  \( 3, \) inclusive, we can try solving for \( x \) with each of
  these seven values of \( y.  \)  When we do so, we find that there
  are only two values of \( y \) for which we get integer solutions
  for \( x.  \)  They are \( y = 3 \) and \( y = -3.  \)  In both cases,
  we get \( x = 6.  \)  Therefore, the solutions to the given equation
  are:

  \[
    x = 6, \qquad y = \pm 3.
  \]
&lt;/p&gt;
<!-- ### -->
&lt;p&gt;
  &lt;a href="https://susam.net/from-diophantine-equation-to-fermats-last-theorem.html"&gt;Read on website&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/mathematics.html&quot;&gt;#mathematics&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/combinatorics.html&quot;&gt;#combinatorics&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/puzzle.html&quot;&gt;#puzzle&lt;/a&gt;
&lt;/p&gt;
<!-- END HTML -->
    </content>
  </entry>
  <entry>
    <title>Stack Overwriting Function</title>
    <link href="https://susam.net/stack-overwriting-function.html"/>
    <id>urn:uuid:f3b1492a-0182-4341-a30d-0fce7a3d6f70</id>
    <updated>2010-07-28T00:00:00Z</updated>
    <content type="html">
<!-- BEGIN HTML -->
&lt;h2 id=&quot;skipping-over-a-function-call&quot;&gt;Skipping Over a Function Call&lt;/h2&gt;
&lt;p&gt;
  Here is a C puzzle that involves some analysis of the machine code
  generated from it followed by manipulation of the runtime stack.
  The solution to this puzzle is &lt;em&gt;implementation-dependent&lt;/em&gt;.
  Here is the puzzle:
&lt;/p&gt;
&lt;div class=&quot;highlight&quot;&gt;
&lt;p&gt;
  Consider this C code:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;

void f()
{
}

int main()
{
    printf(&quot;1\n&quot;);
    f();
    printf(&quot;2\n&quot;);
    printf(&quot;3\n&quot;);
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  Define the function &lt;code&gt;f()&lt;/code&gt; such that the output of the
  above code is:
&lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;1
3&lt;/samp&gt;&lt;/pre&gt;
&lt;p&gt;
  Printing &lt;code&gt;3&lt;/code&gt; in &lt;code&gt;f()&lt;/code&gt; and exiting is not
  allowed as a solution.
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
  &lt;em&gt;If you want to think about this problem, this is a good time to
  pause and think about it.  There are spoilers ahead.&lt;/em&gt;
&lt;/p&gt;
&lt;p&gt;
  The solution essentially involves figuring out what code we can
  place in the body of &lt;code&gt;f()&lt;/code&gt; such that it causes the
  program to skip over the machine code generated for
  the &lt;code&gt;printf(&quot;2\n&quot;)&lt;/code&gt; operation.  I&apos;ll share two solutions
  for two different implementations:
&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;
    gcc 4.3.2 on 64-bit Debian 5.0.3 running on 64-bit Intel Core 2
    Duo.
  &lt;/li&gt;
  &lt;li&gt;
    Microsoft Visual Studio 2005 on 32-bit Windows XP running on
    64-bit Intel Core 2 Duo.
  &lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id=&quot;solution-for-gcc&quot;&gt;Solution for GCC&lt;/h2&gt;
&lt;p&gt;
  Let us first see step by step how I approached this problem for GCC.
  We add a statement &lt;code&gt;char a = 7;&lt;/code&gt; to the function
  &lt;code&gt;f()&lt;/code&gt;.  The code looks like this:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;

void f()
{
    char a = 7;
}

int main()
{
    printf(&quot;1\n&quot;);
    f();
    printf(&quot;2\n&quot;);
    printf(&quot;3\n&quot;);
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  There is nothing special about the number &lt;code&gt;7&lt;/code&gt; here.  We
  just want to define a variable in &lt;code&gt;f()&lt;/code&gt; and assign some
  value to it.
&lt;/p&gt;
&lt;p&gt;
  Then we compile the code and analyse the machine code generated for
  &lt;code&gt;f()&lt;/code&gt; and &lt;code&gt;main()&lt;/code&gt; functions.
&lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;$ &lt;kbd&gt;gcc -c overwrite.c &amp;amp;&amp;amp; objdump -d overwrite.o&lt;/kbd&gt;

overwrite.o:     file format elf64-x86-64


Disassembly of section .text:

0000000000000000 &amp;lt;f&amp;gt;:
   0:   55                      push   %rbp
   1:   48 89 e5                mov    %rsp,%rbp
   &lt;span class=&quot;hl&quot;&gt;4:   c6 45 ff 07             movb   $0x7,-0x1(%rbp)&lt;/span&gt;
   8:   c9                      leaveq
   9:   c3                      retq

000000000000000a &amp;lt;main&amp;gt;:
   a:   55                      push   %rbp
   b:   48 89 e5                mov    %rsp,%rbp
   e:   bf 00 00 00 00          mov    $0x0,%edi
  13:   e8 00 00 00 00          callq  18 &amp;lt;main+0xe&amp;gt;
  18:   b8 00 00 00 00          mov    $0x0,%eax
  1d:   e8 00 00 00 00          callq  22 &amp;lt;main+0x18&amp;gt;
  &lt;span class=&quot;hl&quot;&gt;22:   bf 00 00 00 00          mov    $0x0,%edi
  27:   e8 00 00 00 00          callq  2c &amp;lt;main+0x22&amp;gt;&lt;/span&gt;
  2c:   bf 00 00 00 00          mov    $0x0,%edi
  31:   e8 00 00 00 00          callq  36 &amp;lt;main+0x2c&amp;gt;
  36:   b8 00 00 00 00          mov    $0x0,%eax
  3b:   c9                      leaveq
  3c:   c3                      retq&lt;/samp&gt;&lt;/pre&gt;
&lt;p&gt;
  When &lt;code&gt;main()&lt;/code&gt; calls &lt;code&gt;f()&lt;/code&gt;, the microprocessor
  saves the return address (where the control must return to after
  &lt;code&gt;f()&lt;/code&gt; is executed) in stack.  The line at offset
  &lt;samp&gt;1d&lt;/samp&gt; in the listing above for &lt;code&gt;main()&lt;/code&gt; is the
  call to &lt;code&gt;f()&lt;/code&gt;.  After &lt;code&gt;f()&lt;/code&gt; is executed, the
  instruction at offset &lt;samp&gt;22&lt;/samp&gt; is executed.  Therefore the
  return address that is saved on stack is the address at which the
  instruction at offset
  &lt;samp&gt;22&lt;/samp&gt; would be present at runtime.
&lt;/p&gt;
&lt;p&gt;
  The instructions at offsets &lt;samp&gt;22&lt;/samp&gt; and &lt;samp&gt;27&lt;/samp&gt; are
  the instructions for the &lt;code&gt;printf(&quot;2\n&quot;)&lt;/code&gt; call.  These are
  the instructions we want to skip over.  In other words, we want to
  modify the return address in the stack from the address of the
  instruction at offset &lt;samp&gt;22&lt;/samp&gt; to that of the instruction at
  offset &lt;samp&gt;2c&lt;/samp&gt;.  This is equivalent to skipping 10 bytes
  (0x2c - 0x22 = 10) of machine code or adding 10 to the return
  address saved in the stack.
&lt;/p&gt;
&lt;p&gt;
  Now how do we get hold of the return address saved in the stack when
  &lt;code&gt;f()&lt;/code&gt; is being executed?  This is where the variable
  &lt;code&gt;a&lt;/code&gt; we defined in &lt;code&gt;f()&lt;/code&gt; helps.  The instruction
  at offset &lt;samp&gt;4&lt;/samp&gt; is the instruction generated for
  assigning &lt;code&gt;7&lt;/code&gt; to the variable &lt;code&gt;a&lt;/code&gt;.
&lt;/p&gt;
&lt;p&gt;
  From the knowledge of how microprocessor works and from the machine
  code generated for &lt;code&gt;f()&lt;/code&gt;, we find that the following
  sequence of steps are performed during the call to &lt;code&gt;f()&lt;/code&gt;:
&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;
    The microprocessor saves the return address by pushing the content
    of RIP (instruction pointer) register into the stack.
  &lt;/li&gt;
  &lt;li&gt;
    The function &lt;code&gt;f()&lt;/code&gt; pushes the content of the RBP (base
    pointer) register into the stack.
  &lt;/li&gt;
  &lt;li&gt;
    The function &lt;code&gt;f()&lt;/code&gt; copies the content of the RSP (stack
    pointer) register to the RBP register.
  &lt;/li&gt;
  &lt;li&gt;
    The function &lt;code&gt;f()&lt;/code&gt; stores the byte value &lt;code&gt;7&lt;/code&gt;
    at the memory address specified by the content of RBP minus 1.
    This achieves the assignment of the value &lt;code&gt;7&lt;/code&gt; to the
    variable &lt;code&gt;a&lt;/code&gt;.
  &lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
  After &lt;code&gt;7&lt;/code&gt; is assigned to the variable &lt;code&gt;a&lt;/code&gt;, the
  stack is in the following state:
&lt;/p&gt;
&lt;table class=&quot;grid center textcenter&quot;&gt;
  &lt;tr&gt;
    &lt;th&gt;Address&lt;/th&gt;
    &lt;th&gt;Content&lt;/th&gt;
    &lt;th&gt;Size (in bytes)&lt;/th&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;&lt;code&gt;&amp;amp;a + 5&lt;/code&gt;&lt;/td&gt;
    &lt;td&gt;Return address (old RIP)&lt;/td&gt;
    &lt;td&gt;8&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;&lt;code&gt;&amp;amp;a + 1&lt;/code&gt;&lt;/td&gt;
    &lt;td&gt;Old base pointer (old RBP)&lt;/td&gt;
    &lt;td&gt;8&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;&lt;code&gt;&amp;amp;a&lt;/code&gt;&lt;/td&gt;
    &lt;td&gt;Variable &lt;code&gt;a&lt;/code&gt;&lt;/td&gt;
    &lt;td&gt;1&lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;
&lt;p&gt;
  If we add 9 to the address of the variable &lt;code&gt;a&lt;/code&gt;, i.e.
  &lt;code&gt;&amp;amp;a&lt;/code&gt;, we get the address where the return address is
  stored.  We saw earlier that if we increment this return address by
  10 bytes, it solves the problem.  Therefore here is the solution
  code:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;

void f()
{
    char a;
    (&amp;amp;a)[9] += 10;
}

int main()
{
    printf(&quot;1\n&quot;);
    f();
    printf(&quot;2\n&quot;);
    printf(&quot;3\n&quot;);
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  Finally, we compile and run this code and confirm that the solution
  works fine:
&lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;$ &lt;kbd&gt;gcc overwrite.c &amp;amp;&amp;amp; ./a.out&lt;/kbd&gt;
1
3&lt;/samp&gt;&lt;/pre&gt;
&lt;h2 id=&quot;solution-for-visual-studio&quot;&gt;Solution for Visual Studio&lt;/h2&gt;
&lt;p&gt;
  Now we will see another example solution, this time for Visual
  Studio 2005.
&lt;/p&gt;
&lt;p&gt;
  Like before we define a variable &lt;code&gt;a&lt;/code&gt; in &lt;code&gt;f()&lt;/code&gt;.
  The code now looks like this:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;

void f()
{
    char a = 7;
}

int main()
{
    printf(&quot;1\n&quot;);
    f();
    printf(&quot;2\n&quot;);
    printf(&quot;3\n&quot;);
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  Then we compile the code and analyse the machine code generated from
  it.
&lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;C:\&amp;gt;&lt;kbd&gt;cl overwrite.c&lt;/kbd&gt;
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.42
for 80x86
Copyright (C) Microsoft Corporation.  All rights reserved.

overwrite.c
Microsoft (R) Incremental Linker Version 8.00.50727.42
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:overwrite.exe
overwrite.obj

C:\&amp;gt;&lt;kbd&gt;dumpbin /disasm overwrite.obj&lt;/kbd&gt;
Microsoft (R) COFF/PE Dumper Version 8.00.50727.42
Copyright (C) Microsoft Corporation.  All rights reserved.


Dump of file overwrite.obj

File Type: COFF OBJECT

_f:
  00000000: 55                 push        ebp
  00000001: 8B EC              mov         ebp,esp
  00000003: 51                 push        ecx
  &lt;span class=&quot;hl&quot;&gt;00000004: C6 45 FF 07        mov         byte ptr [ebp-1],7&lt;/span&gt;
  00000008: 8B E5              mov         esp,ebp
  0000000A: 5D                 pop         ebp
  0000000B: C3                 ret
  0000000C: CC                 int         3
  0000000D: CC                 int         3
  0000000E: CC                 int         3
  0000000F: CC                 int         3
_main:
  00000010: 55                 push        ebp
  00000011: 8B EC              mov         ebp,esp
  00000013: 68 00 00 00 00     push        offset $SG2224
  00000018: E8 00 00 00 00     call        _printf
  0000001D: 83 C4 04           add         esp,4
  00000020: E8 00 00 00 00     call        _f
  &lt;span class=&quot;hl&quot;&gt;00000025: 68 00 00 00 00     push        offset $SG2225
  0000002A: E8 00 00 00 00     call        _printf
  0000002F: 83 C4 04           add         esp,4&lt;/span&gt;
  00000032: 68 00 00 00 00     push        offset $SG2226
  00000037: E8 00 00 00 00     call        _printf
  0000003C: 83 C4 04           add         esp,4
  0000003F: 33 C0              xor         eax,eax
  00000041: 5D                 pop         ebp
  00000042: C3                 ret

  Summary

           B .data
          57 .debug$S
          2F .drectve
          43 .text&lt;/samp&gt;&lt;/pre&gt;
&lt;p&gt;
  Just like in the previous &lt;code&gt;objdump&lt;/code&gt; listing, in this
  listing too, the instruction at offset &lt;code&gt;4&lt;/code&gt; shows where
  the variable &lt;code&gt;a&lt;/code&gt; is allocated and the instructions at
  offsets &lt;code&gt;25&lt;/code&gt;, &lt;code&gt;2A&lt;/code&gt; and &lt;code&gt;2F&lt;/code&gt; show
  the instructions we want to skip, i.e. instead of returning to the
  instruction at offset &lt;code&gt;25&lt;/code&gt;, we want the microprocessor to
  return to the instruction at offset &lt;code&gt;32&lt;/code&gt;.  This involves
  skipping 13 bytes (0x32 - 0x25 = 13) of machine code.
&lt;/p&gt;
&lt;p&gt;
  Unlike the previous &lt;code&gt;objdump&lt;/code&gt; listing, in this listing we
  see that the Visual Studio I am using is a 32-bit on, so it
  generates machine code to use 32-bit registers like EBP, ESP, etc.
  Thus the stack looks like this after &lt;code&gt;7&lt;/code&gt; is assigned to
  the variable
  &lt;code&gt;a&lt;/code&gt;:
&lt;/p&gt;
&lt;table class=&quot;grid center textcenter&quot;&gt;
  &lt;tr&gt;
    &lt;th&gt;Address&lt;/th&gt;
    &lt;th&gt;Content&lt;/th&gt;
    &lt;th&gt;Size (in bytes)&lt;/th&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;&lt;code&gt;&amp;amp;a + 5&lt;/code&gt;&lt;/td&gt;
    &lt;td&gt;Return address (old EIP)&lt;/td&gt;
    &lt;td&gt;4&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;&lt;code&gt;&amp;amp;a + 1&lt;/code&gt;&lt;/td&gt;
    &lt;td&gt;Old base pointer (old EBP)&lt;/td&gt;
    &lt;td&gt;4&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;&lt;code&gt;&amp;amp;a&lt;/code&gt;&lt;/td&gt;
    &lt;td&gt;Variable &lt;code&gt;a&lt;/code&gt;&lt;/td&gt;
    &lt;td&gt;1&lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;
&lt;p&gt;
  If we add 5 to the address of the variable &lt;code&gt;a&lt;/code&gt;, i.e.
  &lt;code&gt;&amp;amp;a&lt;/code&gt;, we get the address where the return address is
  stored.  Here is the solution code:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;

void f()
{
    char a;
    (&amp;amp;a)[5] += 13;
}

int main()
{
    printf(&quot;1\n&quot;);
    f();
    printf(&quot;2\n&quot;);
    printf(&quot;3\n&quot;);
    return 0;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  Finally, we compile and run this code and confirm that the solution
  works fine:
&lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;C:\&amp;gt;&lt;kbd&gt;cl /w overwrite.c&lt;/kbd&gt;
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.42
for 80x86
Copyright (C) Microsoft Corporation.  All rights reserved.

overwrite.c
Microsoft (R) Incremental Linker Version 8.00.50727.42
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:overwrite.exe
overwrite.obj

C:\&amp;gt;&lt;kbd&gt;overwrite.exe&lt;/kbd&gt;
1
3&lt;/samp&gt;&lt;/pre&gt;
&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;
  The machine code that the compiler generates for a given C code is
  highly dependent on the implementation of the compiler.  In the two
  examples above, we have two different solutions for two different
  compilers.
&lt;/p&gt;
&lt;p&gt;
  Even with the same brand of compiler, the way it generates machine
  code for a given code may change from one version of the compiler to
  another.  Therefore, it is very likely that the above solution would
  not work on another system (such as your system) even if you use the
  same compiler that I am using in the examples above.
&lt;/p&gt;
&lt;p&gt;
  However, we can arrive at the solution for an implementation of the
  compiler by determining what number to add to &lt;code&gt;&amp;amp;a&lt;/code&gt; to
  get the address where the return address is saved on stack and what
  number to add to this return address to make it point to the
  instruction we want to skip to after &lt;code&gt;f()&lt;/code&gt; returns.
&lt;/p&gt;
<!-- ### -->
&lt;p&gt;
  &lt;a href="https://susam.net/stack-overwriting-function.html"&gt;Read on website&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/c.html&quot;&gt;#c&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/programming.html&quot;&gt;#programming&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/technology.html&quot;&gt;#technology&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/puzzle.html&quot;&gt;#puzzle&lt;/a&gt;
&lt;/p&gt;
<!-- END HTML -->
    </content>
  </entry>
  <entry>
    <title>Illiteracy and Digital Weighing Scale</title>
    <link href="https://susam.net/illiteracy-and-digital-weighing-scale.html"/>
    <id>urn:uuid:1c7d31d7-3557-4d01-ab5f-39287e6349db</id>
    <updated>2010-07-06T00:00:00Z</updated>
    <content type="html">
<!-- BEGIN HTML -->
&lt;p&gt;
  Here is a real life problem from a silica bricks factory in a small
  industrial town in India.  There are illiterate workers who cannot
  identify decimal digits.  The management team of the factory is
  trying to figure if there is a way for these workers to operate a
  digital weighing scale to fill buckets with a certain mass of a
  given material.  For example, they may be asked to fill 5.3&amp;nbsp;kg
  of a certain material in the bucket, i.e. decimal fractions are
  involved.
&lt;/p&gt;
&lt;p&gt;
  If the factory were using a beam balance, this would have been an
  easy problem to solve.  The workers could then place the required
  weight in one pan and keep pouring the material in the other pan
  until the beam appears to be balanced.
&lt;/p&gt;
&lt;p&gt;
  However this factory uses a digital weighing scale which involves
  recognising decimal digits to read the measurement.  What do you
  think is the easiest way to train the workers to do their job
  without having to teach them how to count?
&lt;/p&gt;
&lt;p&gt;
  I have a solution in mind which would involve configuring the
  digital weighing scale in a certain way for every measurement the
  workers have to make.  I will propose this solution to the
  management team of the factory.  But I would like to know any
  suggestions you have and take them into account as well before
  proposing my solution.  I will also share the solution I have in
  mind after learning about your suggestions.
&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;
  &lt;strong&gt;Update on 08&amp;nbsp;July&amp;nbsp;2010:&lt;/strong&gt; Prunthaban has
  suggested a solution in the
  &lt;a href=&quot;comments/illiteracy-and-digital-weighing-scale.html#5&quot;&gt;comments&lt;/a&gt;
  section which is pretty much what I had in mind too.  I will propose
  this solution to the factory.  The solution works like this: Say the
  worker has to fill 5.3 kg of a certain material into the bucket.  A
  literate supervisor first places 5.3&amp;nbsp;kg of that material on the
  weighing scale.  The instrument now shows &quot;5.3&amp;nbsp;kg&quot; on its
  display.  Now the remainder of the solution assumes that the digital
  weighing balance has a calibration wheel to calibrate the
  instrument.  The supervisor turns the calibration wheel until the
  display shows &quot;0.0&quot;&amp;nbsp;kg while the 5.3&amp;nbsp;kg of material is
  still placed on it.  Now the material is removed from the balance and
  the display shows &quot;-5.3&amp;nbsp;kg&quot;.  Now all a worker needs to do is
  pour the given material on this calibrated balance until the display
  shows &quot;0.0&amp;nbsp;kg&quot;.  As long as the workers can be taught to
  recognise the digit &quot;0&quot;, this solution should work fine.
&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;
  &lt;strong&gt;Update on 05&amp;nbsp;Aug&amp;nbsp;2010:&lt;/strong&gt; The above solution
  was successfully implemented in OCL India Limited, the silica bricks
  factory where this problem was faced.  The digital weighing balance
  involved in the problem indeed had a calibration wheel, so the above
  solution worked for them.  Thank you, Prunthaban and others who
  participated in this discussion.
&lt;/p&gt;
<!-- ### -->
&lt;p&gt;
  &lt;a href="https://susam.net/illiteracy-and-digital-weighing-scale.html"&gt;Read on website&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/miscellaneous.html&quot;&gt;#miscellaneous&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/puzzle.html&quot;&gt;#puzzle&lt;/a&gt;
&lt;/p&gt;
<!-- END HTML -->
    </content>
  </entry>
  <entry>
    <title>ADAC and HE Puzzles from GEB</title>
    <link href="https://susam.net/adac-and-he-puzzles-from-geb.html"/>
    <id>urn:uuid:284dbf6c-422c-43a1-bbc1-417e60733706</id>
    <updated>2009-05-16T00:00:00Z</updated>
    <content type="html">
<!-- BEGIN HTML -->
&lt;p&gt;
  I have been reading
  &lt;em&gt;&lt;a href=&quot;http://en.wikipedia.org/wiki/G%C3%B6del,_Escher,_Bach&quot;
  class=&quot;title&quot;&gt;G&amp;ouml;del, Escher, Bach: An Eternal Golden
  Braid&lt;/a&gt;&lt;/em&gt; by Douglas R. Hofstadter for a few weeks.  The book
  follows an interesting format of alternating between chapters and
  dialogues between imaginary charaters.  In the words of the author:
&lt;/p&gt;
&lt;blockquote&gt;
  The long and the short of it is that I eventually decided - but this
  took many months - that the optimal structure would be a strict
  alternation between chapters and dialogues.  Once that was clear,
  then I had the joyous task of trying to pinpoint the most crucial
  ideas that I wanted to get across to my readers and then somehow
  embodying them in both the form and the content of fanciful, often
  punning dialogues between Achilles and the Tortoise (plus a few new
  friends).
&lt;/blockquote&gt;
&lt;p&gt;
  After the second chapter (Chapter II: Meaning and Form in
  Mathematics) there is a dialogue between Achilles and the Tortoise
  on telephone.  The title of the dialogue is &lt;em&gt;Sonata for
  Unaccompanied Achilles&lt;/em&gt;.  The text shows the transcript of only
  one end of the call, only what Achilles speaks.  The Tortoise is at
  the far end of the call.  The sentences spoken by the Tortoise at
  the other end are not present in the text.  This makes the reading
  experience very interesting as we keep guessing about what is going
  on at the other end.
&lt;/p&gt;
&lt;p&gt;
  It starts in this manner:
&lt;/p&gt;
&lt;blockquote&gt;
  &lt;em&gt;Achilles:&lt;/em&gt; Hello, this is Achilles.&lt;br&gt;
  &lt;em&gt;Achilles:&lt;/em&gt; Oh, hello, Mr. T. How are you?&lt;br&gt;
  &lt;em&gt;Achilles:&lt;/em&gt; A torticollis?  Oh, I&apos;m sorry to hear it.  Do you
  have any idea what caused it?
&lt;/blockquote&gt;
&lt;p&gt;
  As the dialogue proceeds, they share a few puzzles.  Here is the
  first one from the Tortoise.
&lt;/p&gt;
&lt;blockquote&gt;
  &lt;em&gt;Achilles:&lt;/em&gt; A word with the letters &apos;A&apos;, &apos;D&apos;, &apos;A&apos;, &apos;C&apos;
  consecutively inside it &amp;hellip; Hmm &amp;hellip; What about
  &quot;abracadabra&quot;?&lt;br&gt;
  &lt;em&gt;Achilles:&lt;/em&gt; True, &quot;ADAC&quot; occurs backwards, not forwards, in
  that word.&lt;br&gt;
  &lt;em&gt;Achilles:&lt;/em&gt; Hours and hours?  It sounds like I&apos;m in for a
  long puzzle, then.  Where did you hear this infernal riddle?
&lt;/blockquote&gt;
&lt;p&gt;
  Here is the second puzzle from Achilles:
&lt;/p&gt;
&lt;blockquote&gt;
  &lt;em&gt;Achilles:&lt;/em&gt; Say, I once heard a word puzzle a little bit like
  this one.  Do you want to hear it?  Or would it just drive you
  further into distraction?&lt;br&gt;
  &lt;em&gt;Achilles:&lt;/em&gt; I agree - can&apos;t do any harm.  Here it is: What&apos;s
  a word that begins with the letters &quot;HE&quot; and also ends with
  &quot;HE&quot;?&lt;br&gt;
  &lt;em&gt;Achilles:&lt;/em&gt; Very ingenious - but that&apos;s almost cheating.
  It&apos;s certainly not what I meant!&lt;br&gt;
  &lt;em&gt;Achilles:&lt;/em&gt; Of course you&apos;re right - it fulfills the
  conditions, but it&apos;s a sort of &quot;degenerate&quot; solution.  There&apos;s
  another solution which I had in mind.&lt;br&gt;
  &lt;em&gt;Achilles:&lt;/em&gt; That&apos;s exactly it!  How did you come up with it
  so fast?&lt;br&gt;
  &lt;em&gt;Achilles:&lt;/em&gt; So here&apos;s a case where having a headache actually
  might have helped you, rather than hindering you.  Excellent!  But
  I&apos;m still in the dark on your &quot;ADAC&quot; puzzle.
&lt;/blockquote&gt;
&lt;p&gt;
  &lt;em&gt;If you want to think about these puzzles, this is a good time to
  pause and think about them.  There are spoilers ahead.&lt;/em&gt;
&lt;/p&gt;
&lt;p&gt;
  It did not take much time for me to solve the puzzle because I
  cheated with the word list file available on Linux distributions.
  Here is what I found with my Debian 5.0 (lenny) system:
&lt;/p&gt;
&lt;pre&gt;&lt;samp&gt;$ &lt;kbd&gt;grep &apos;adac&apos; /usr/share/dict/words&lt;/kbd&gt;
headache
headache&apos;s
headaches
$ &lt;kbd&gt;grep &apos;^he.*he$&apos; /usr/share/dict/words&lt;/kbd&gt;
headache
heartache&lt;/samp&gt;&lt;/pre&gt;
&lt;p&gt;
  The answers to both puzzles seem to be &quot;HEADACHE&quot;.  Take another
  look at the last sentence in the dialogue above.  It makes sense now
  as Achilles says that having a &lt;em&gt;headache&lt;/em&gt; might have helped
  the Tortoise.
&lt;/p&gt;
&lt;p&gt;
  Later in the dialogue the Tortoise offers &lt;em&gt;figure&lt;/em&gt; and
  &lt;em&gt;ground&lt;/em&gt; as hints to the &quot;ADAC&quot; puzzle.
&lt;/p&gt;
&lt;blockquote&gt;
  &lt;em&gt;Achilles:&lt;/em&gt; Well, normally I don&apos;t like hints, but all right.
  What&apos;s your hint?&lt;br&gt;
  &lt;em&gt;Achilles:&lt;/em&gt; I don&apos;t know what you mean by &quot;figure&quot; and
  &quot;ground&quot; in this case.&lt;br&gt;
  &lt;em&gt;Achilles:&lt;/em&gt; Certainly I know Mosaic II!  I know ALL of
  Escher&apos;s works.  After all, he&apos;s my favorite artist.  In any case,
  I&apos;ve got a print of Mosaic II hanging on my wall, in plain view from
  here.&lt;br&gt;
  &lt;em&gt;Achilles:&lt;/em&gt; Yes, I see all the black animals.&lt;br&gt;
  &lt;em&gt;Achilles:&lt;/em&gt; Yes, I also see how their &quot;negative&quot; space -
  what&apos;s left out - defines the white animals.&lt;br&gt;
  &lt;em&gt;Achilles:&lt;/em&gt; So THAT&apos;s what you mean by &quot;figure&quot; and &quot;ground&quot;.
  But what does that have to do with the &quot;ADAC&quot; puzzle?&lt;br&gt;
  &lt;em&gt;Achilles:&lt;/em&gt; Oh, this is too tricky to me.  I think I&apos;M
  starting to get a headache.
&lt;/blockquote&gt;
&lt;p&gt;
  The famous painting discussed in the dialogue can be found
  here: &lt;a href=&quot;https://www.wikiart.org/en/m-c-escher/mosaic-ii&quot;&gt;https://www.wikiart.org/en/m-c-escher/mosaic-ii&lt;/a&gt;.
  We can see how the black animals form the &lt;em&gt;figure&lt;/em&gt; (the
  positive space) and how the background or &lt;em&gt;ground&lt;/em&gt; (the
  negative space) beautifully fits all the white animals.
&lt;/p&gt;
&lt;p&gt;
  The &lt;em&gt;figure&lt;/em&gt; and &lt;em&gt;ground&lt;/em&gt; in hints make sense now.
  The first puzzle has &quot;ADAC&quot; in the question.  Let us consider &quot;ADAC&quot;
  as the figure or the positive space.  If we remove &quot;ADAC&quot; from
  &quot;HEADACHE&quot;, we are left with the ground or negative space, which
  consists of &quot;HE&quot; and &quot;HE&quot; at the beginning and the end of the word.
  The &lt;em&gt;figure&lt;/em&gt; is used in the first puzzle and
  the &lt;em&gt;ground&lt;/em&gt; is used in the second puzzle.
&lt;/p&gt;
&lt;p&gt;
  By the way, what is the first answer from the Tortoise that Achilles
  finds very ingenious but degenerate?  I believe, it is &quot;HE&quot; as this
  word both begins and ends with &quot;HE&quot;.
&lt;/p&gt;
&lt;p&gt;
  The funny thing about this dialogue is that both of them asked two
  puzzles to each other without knowing that the answers to them were
  the same.  A similar thing happened to me when a colleague of mine
  and I challenged each other with combinatorics puzzles.  See this
  blog post for the story:
  &lt;a href=&quot;combinatorics-coincidence.html&quot;&gt;Combinatorics Coincidence&lt;/a&gt;.
&lt;/p&gt;
<!-- ### -->
&lt;p&gt;
  &lt;a href="https://susam.net/adac-and-he-puzzles-from-geb.html"&gt;Read on website&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/miscellaneous.html&quot;&gt;#miscellaneous&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/book.html&quot;&gt;#book&lt;/a&gt; |
  &lt;a href=&quot;https://susam.net/tag/puzzle.html&quot;&gt;#puzzle&lt;/a&gt;
&lt;/p&gt;
<!-- END HTML -->
    </content>
  </entry>
</feed>
