{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "63fa36e3",
   "metadata": {},
   "source": [
    "# Part 3. Points of finite order and minimal polynomials\n",
    "\n",
    "A point $P$ of the circle has **order** $n$ if $P^n=(1,0)$ and no smaller positive power gives $(1,0)$.\n",
    "On the real circle, the points of order $n$ are the vertices of the regular $n$-gon inscribed in the circle,\n",
    "$\\bigl(\\cos\\frac{2\\pi k}{n},\\sin\\frac{2\\pi k}{n}\\bigr)$ with $\\gcd(k,n)=1$ — in the language of complex\n",
    "numbers, these are the primitive $n$th roots of unity. From Part 2 we know that\n",
    "\n",
    "$$\n",
    "P^n=(1,0)\\iff T_n(a)=1\\ \\text{ and }\\ b\\,U_{n-1}(a)=0,\n",
    "$$\n",
    "\n",
    "so the first coordinates of the points of order $n$ are roots of the polynomial $T_n(x)-1$. In this\n",
    "part we use this to extract the minimal polynomials of the numbers $\\cos\\frac{2\\pi}{n}$, build formulas\n",
    "in radicals for $n=5$ and $n=15$ (the latter by multiplying points), reconstruct Gauss’s construction\n",
    "of the 17-gon, and check for which $n$ formulas using only square roots exist."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d12ab5c0",
   "metadata": {},
   "outputs": [],
   "source": [
    "from functools import cache\n",
    "\n",
    "import sympy as sp\n",
    "\n",
    "x, z = sp.symbols(\"x z\")\n",
    "\n",
    "\n",
    "def m(P, Q):\n",
    "    \"\"\"Prawo grupowe okręgu (część 1).\"\"\"\n",
    "    a, b = P\n",
    "    c, d = Q\n",
    "    return (a * c - b * d, a * d + b * c)\n",
    "\n",
    "\n",
    "def T(n):\n",
    "    return sp.chebyshevt(n, x)       # te same wielomiany co w części 2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "34211028",
   "metadata": {},
   "source": [
    "## Factoring $T_n(x)-1$\n",
    "\n",
    "Let us start with an example. We factor $T_{12}(x)-1$ into irreducible factors over $\\mathbb{Q}$ and see\n",
    "which points of the circle correspond to the individual factors."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8af82c46",
   "metadata": {},
   "outputs": [],
   "source": [
    "stala, czynniki = sp.factor_list(T(12) - 1)\n",
    "print(\"T_12(x) - 1 =\", stala, \"·\",\n",
    "      \" · \".join(f\"({f})^{k}\" if k > 1 else f\"({f})\" for f, k in czynniki))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f3515e6e",
   "metadata": {},
   "source": [
    "Each factor corresponds to one divisor $d$ of $12$, that is, to the points of order exactly $d$:\n",
    "$x-1$ is the point $(1,0)$ ($d=1$), $x+1$ is $(-1,0)$ ($d=2$), $2x+1$ gives the vertices of the triangle ($d=3$),\n",
    "$x$ — of the square ($d=4$), $2x-1$ — of the hexagon ($d=6$), and $4x^2-3$ — of the dodecagon ($d=12$). The factors\n",
    "other than $x\\pm1$ appear squared, because the points $P$ and $P^{-1}=(a,-b)$ have the same first\n",
    "coordinate; the points $(\\pm1,0)$ are their own inverses.\n",
    "\n",
    "## The minimal polynomial of $\\cos\\frac{2\\pi}{n}$\n",
    "\n",
    "Let $\\Psi_n$ denote the monic irreducible factor of $T_n(x)-1$ that divides no\n",
    "$T_d(x)-1$ for proper divisors $d$ of $n$. It is the factor of the “new” points, of order exactly\n",
    "$n$, that is, the minimal polynomial of $\\cos\\frac{2\\pi}{n}$ over $\\mathbb{Q}$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "303d58f3",
   "metadata": {},
   "outputs": [],
   "source": [
    "@cache\n",
    "def Psi(n):\n",
    "    \"\"\"Wielomian minimalny cos(2π/n): nowy czynnik T_n(x) - 1.\"\"\"\n",
    "    for f, _ in sp.factor_list(T(n) - 1)[1]:\n",
    "        if not any(sp.rem(T(d) - 1, f, x) == 0 for d in sp.divisors(n)[:-1]):\n",
    "            return sp.Poly(f, x).monic()\n",
    "\n",
    "\n",
    "print(f\"{'n':>3} {'stopień Ψ_n':>12} {'φ(n)/2':>7}  = minimal_polynomial\")\n",
    "tabela = []\n",
    "for n in range(3, 21):\n",
    "    mp = sp.Poly(sp.minimal_polynomial(sp.cos(2 * sp.pi / n), x), x).monic()\n",
    "    tabela.append((n, Psi(n).degree(), int(sp.totient(n)) // 2, Psi(n) == mp))\n",
    "    print(f\"{n:>3} {tabela[-1][1]:>12} {tabela[-1][2]:>7}  {tabela[-1][3]}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "60cc4e45",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert all(st == ph and ok for _, st, ph, ok in tabela)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c84e0299",
   "metadata": {},
   "source": [
    "The degree of $\\Psi_n$ is $\\varphi(n)/2$ (for $n\\ge3$): there are $\\varphi(n)$ points of order $n$, and the pairs\n",
    "$P,P^{-1}$ share the same $\\cos$. That $\\Psi_n$ is irreducible follows from the irreducibility of\n",
    "cyclotomic polynomials — here SymPy factors the polynomial over $\\mathbb{Q}$ and confirms it for\n",
    "every $n$ in the table.\n",
    "\n",
    "A consequence for rational points: $\\cos\\frac{2\\pi}{n}$ is rational only when $\\Psi_n$ has\n",
    "degree $1$, that is, for $n\\in\\{1,2,3,4,6\\}$ (Niven’s theorem, 1956). If $\\sin$ is also required to be\n",
    "rational, we are left with $n\\in\\{1,2,4\\}$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72fb6a9e",
   "metadata": {},
   "outputs": [],
   "source": [
    "wymierne_cos = [n for n in range(1, 61) if Psi(n).degree() == 1]\n",
    "wymierne_oba = [n for n in wymierne_cos\n",
    "                if sp.sin(2 * sp.pi / n).is_rational]\n",
    "print(\"cos(2π/n) wymierny dla n ≤ 60:\", wymierne_cos)\n",
    "print(\"cos i sin wymierne:\", wymierne_oba)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5af064d5",
   "metadata": {},
   "source": [
    "So the group $S^1(\\mathbb{Q})$ has only four points of finite order: $(\\pm1,0)$ and $(0,\\pm1)$.\n",
    "All other rational points, such as $(3/5,4/5)$ from Part 1, have infinite order.\n",
    "(The computation covers $n\\le60$; for larger $n$, the fact that $\\varphi(n)>2$ suffices.)\n",
    "\n",
    "## The pentagon: a formula in radicals\n",
    "\n",
    "$\\Psi_5$ is quadratic, so we solve it with the quadratic formula and get $\\sin$ from the equation of the circle."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7f138d23",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Ψ_5 =\", Psi(5).as_expr())\n",
    "c5 = max(sp.solve(Psi(5).as_expr(), x), key=lambda r: r.evalf())\n",
    "s5 = sp.sqrt(10 + 2 * sp.sqrt(5)) / 4\n",
    "print(\"cos(2π/5) =\", c5, \"   sin(2π/5) =\", s5)\n",
    "print(\"na okręgu:\", sp.simplify(c5**2 + s5**2 - 1) == 0)\n",
    "\n",
    "P5 = (c5, s5)\n",
    "Q = (sp.Integer(1), sp.Integer(0))\n",
    "for _ in range(5):\n",
    "    Q = m(Q, P5)\n",
    "print(\"P^5 =\", tuple(sp.radsimp(sp.expand(q)) for q in Q))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43d498da",
   "metadata": {},
   "source": [
    "The check $P^5=(1,0)$ is exact: we expand the products involving square roots and simplify them\n",
    "(`radsimp` removes irrationalities from denominators). No floating-point number appears anywhere.\n",
    "\n",
    "## The 15-gon: multiplying points instead of solving\n",
    "\n",
    "$\\Psi_{15}$ has degree $4$. We could solve an equation of degree 4, but the group offers a shorter route.\n",
    "Since\n",
    "\n",
    "$$\n",
    "\\frac{1}{15}=\\frac{2}{5}-\\frac{1}{3},\n",
    "$$\n",
    "\n",
    "a point of order $15$ is $P_5^{\\,2}\\cdot P_3^{-1}$, where $P_5$ and $P_3$ are points of order $5$ and $3$.\n",
    "We know the coordinates $P_3=(-\\frac12,\\frac{\\sqrt3}{2})$, and we computed $P_5$ a moment ago.\n",
    "Two multiplications in the group suffice."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a2b94113",
   "metadata": {},
   "outputs": [],
   "source": [
    "P3_odwr = (sp.Rational(-1, 2), -sp.sqrt(3) / 2)\n",
    "P15 = tuple(sp.expand(w) for w in m(m(P5, P5), P3_odwr))\n",
    "print(\"cos(2π/15) =\", P15[0])\n",
    "print(\"sin(2π/15) =\", P15[1])\n",
    "\n",
    "mp15 = sp.Poly(sp.minimal_polynomial(P15[0], x), x).monic()\n",
    "print(\"wielomian minimalny = Ψ_15:\", mp15 == Psi(15))\n",
    "print(\"Ψ_15 =\", Psi(15).as_expr())\n",
    "print(\"|różnica z cos(2π/15)| < 10⁻⁵⁰:\",\n",
    "      abs(sp.N(P15[0] - sp.cos(2 * sp.pi / 15), 60)) < sp.Float(\"1e-50\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cc226686",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert mp15 == Psi(15)\n",
    "assert abs(sp.N(P15[0] - sp.cos(2 * sp.pi / 15), 60)) < 1e-50\n",
    "assert abs(sp.N(P15[1] - sp.sin(2 * sp.pi / 15), 60)) < 1e-50"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "54bfaed1",
   "metadata": {},
   "source": [
    "This is the same idea that underlies the Chinese remainder theorem: the group of points whose order divides\n",
    "$15$ is the product of the groups of points whose order divides $3$ and $5$. Euclid constructed the 15-gon\n",
    "with compass and straightedge from the triangle and the pentagon in a similar way: he bisected the arc\n",
    "$\\frac13-\\frac15=\\frac{2}{15}$ of the circle (*Elements*, Book IV, Proposition 16).\n",
    "\n",
    "## The 17-gon: Gaussian periods\n",
    "\n",
    "$\\Psi_{17}$ has degree $8=2^3$. In 1796 Gauss showed that $\\cos\\frac{2\\pi}{17}$ can be\n",
    "obtained by solving **three quadratic equations** in succession, and five years later he described the general\n",
    "method in *Disquisitiones arithmeticae* (1801). We will reconstruct this construction by symbolic\n",
    "computation.\n",
    "\n",
    "We work with $\\zeta=\\cos\\frac{2\\pi}{17}+i\\sin\\frac{2\\pi}{17}$, that is, with the point $P_{17}$ written as\n",
    "a complex number. We compute with polynomials in $z$ modulo\n",
    "$\\Phi_{17}(z)=1+z+\\dots+z^{16}$, since $\\zeta$ satisfies $\\Phi_{17}(\\zeta)=0$. The group\n",
    "$(\\mathbb{Z}/17)^\\times$ is cyclic of order $16$ with generator $3$; its subgroups have orders\n",
    "$8,4,2,1$. A **Gaussian period** of length $f$ is the sum of $\\zeta^j$ over the exponents $j$ in one coset of\n",
    "the subgroup of order $f$. The periods of length $2$ are $\\zeta^j+\\zeta^{-j}=2\\cos\\frac{2\\pi j}{17}$, and we are looking for\n",
    "$2\\cos\\frac{2\\pi}{17}$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "645f352a",
   "metadata": {},
   "outputs": [],
   "source": [
    "p, g = 17, 3\n",
    "PHI = sp.Poly(sp.cyclotomic_poly(p, z), z)\n",
    "POTEGI = [pow(g, k, p) for k in range(p - 1)]       # 3^k mod 17\n",
    "\n",
    "\n",
    "def warstwa(f, i):\n",
    "    \"\"\"Wykładniki okresu długości f o numerze i (i = 0, ..., 16/f - 1).\"\"\"\n",
    "    krok = (p - 1) // f\n",
    "    return sorted(POTEGI[(i + j * krok) % (p - 1)] for j in range(f))\n",
    "\n",
    "\n",
    "def okres(f, i):\n",
    "    return sp.Poly(sum(z**j for j in warstwa(f, i)), z)\n",
    "\n",
    "\n",
    "NAZWY = {8: \"η\", 4: \"λ\", 2: \"μ\"}\n",
    "\n",
    "\n",
    "def w_okresach(w, f):\n",
    "    \"\"\"Zapis w (wielomian od z mod Φ_17) przez okresy długości f.\"\"\"\n",
    "    r = w.rem(PHI)\n",
    "    # 1 = -(z + ... + z^16), więc wyraz wolny przenosimy na z^1, ..., z^16\n",
    "    wsp = [r.coeff_monomial(z**j) - r.coeff_monomial(1) for j in range(p)]\n",
    "    kombinacja = []\n",
    "    for i in range((p - 1) // f):\n",
    "        wart = {wsp[j] for j in warstwa(f, i)}\n",
    "        assert len(wart) == 1, \"w nie jest kombinacją okresów\"\n",
    "        kombinacja.append(wart.pop())\n",
    "    if len(set(kombinacja)) == 1:          # c·(suma wszystkich okresów) = -c\n",
    "        return -kombinacja[0]\n",
    "    return sum(c * sp.Symbol(f\"{NAZWY[f]}{i}\")\n",
    "               for i, c in enumerate(kombinacja))\n",
    "\n",
    "\n",
    "for f in (8, 4, 2):\n",
    "    print(f\"okresy długości {f}:\",\n",
    "          [warstwa(f, i) for i in range((p - 1) // f)])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eb6edb53",
   "metadata": {},
   "source": [
    "The two periods of length $8$, $\\eta_0$ and $\\eta_1$, are the roots of a quadratic equation whose\n",
    "coefficients are their sum and product. The function `w_okresach` expresses such numbers in terms of periods\n",
    "of a given length: when all the coefficients are equal, the result is rational, because\n",
    "$\\sum_{j=1}^{16}\\zeta^j=-1$. We descend one level in the same way: the two periods of length $4$ contained\n",
    "in $\\eta_0$ have sum $\\eta_0$ and a product expressed in terms of periods of length $8$; the two periods of length $2$\n",
    "contained in $\\lambda_0$ have sum $\\lambda_0$ and a product expressed in terms of periods of length $4$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "40cfcc27",
   "metadata": {},
   "outputs": [],
   "source": [
    "eta = [okres(8, i) for i in range(2)]\n",
    "lam = [okres(4, i) for i in range(4)]\n",
    "mu = [okres(2, i) for i in range(8)]\n",
    "\n",
    "print(\"η0 + η1  =\", w_okresach(eta[0] + eta[1], 8))\n",
    "print(\"η0 · η1  =\", w_okresach(eta[0] * eta[1], 8))\n",
    "print(\"λ0 + λ2  =\", w_okresach(lam[0] + lam[2], 8))\n",
    "print(\"λ0 · λ2  =\", w_okresach(lam[0] * lam[2], 8))\n",
    "print(\"λ1 + λ3  =\", w_okresach(lam[1] + lam[3], 8))\n",
    "print(\"λ1 · λ3  =\", w_okresach(lam[1] * lam[3], 8))\n",
    "print(\"μ0 + μ4  =\", w_okresach(mu[0] + mu[4], 4))\n",
    "print(\"μ0 · μ4  =\", w_okresach(mu[0] * mu[4], 4))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "702fdce9",
   "metadata": {},
   "source": [
    "We read off three quadratic equations:\n",
    "\n",
    "* $\\eta_0+\\eta_1=-1$, $\\eta_0\\eta_1=-4$, so $\\eta_{0,1}$ are the roots of $X^2+X-4$;\n",
    "* $\\lambda_0+\\lambda_2=\\eta_0$, $\\lambda_0\\lambda_2=-1$, so $\\lambda_{0,2}$ are the roots of\n",
    "  $X^2-\\eta_0X-1$, and $\\lambda_{1,3}$ are the roots of $X^2-\\eta_1X-1$;\n",
    "* $\\mu_0+\\mu_4=\\lambda_0$, $\\mu_0\\mu_4=\\lambda_1$, so $\\mu_0=2\\cos\\frac{2\\pi}{17}$ is\n",
    "  a root of $X^2-\\lambda_0X+\\lambda_1$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "085ffffe",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "eta0_, eta1_, lam0_, lam1_ = sp.symbols(\"η0 η1 λ0 λ1\")\n",
    "assert w_okresach(eta[0] + eta[1], 8) == -1\n",
    "assert w_okresach(eta[0] * eta[1], 8) == -4\n",
    "assert w_okresach(lam[0] + lam[2], 8) == eta0_\n",
    "assert w_okresach(lam[0] * lam[2], 8) == -1\n",
    "assert w_okresach(lam[1] + lam[3], 8) == eta1_\n",
    "assert w_okresach(lam[1] * lam[3], 8) == -1\n",
    "assert w_okresach(mu[0] + mu[4], 4) == lam0_\n",
    "assert w_okresach(mu[0] * mu[4], 4) == lam1_"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2f6b8736",
   "metadata": {},
   "source": [
    "Now we solve the three quadratic equations in turn. At each level we have to choose one of the two\n",
    "roots; we choose the one that agrees with the approximate value of the period (this is the only place\n",
    "where we use approximate numbers, and only to choose the sign)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "16b41f57",
   "metadata": {},
   "outputs": [],
   "source": [
    "import cmath\n",
    "\n",
    "zeta = cmath.exp(2j * cmath.pi / p)\n",
    "\n",
    "\n",
    "def wartosc(okres_poly):\n",
    "    return sum(complex(c) * zeta**k for (k,), c in okres_poly.terms()).real\n",
    "\n",
    "\n",
    "def pierwiastek(s, q, cel):\n",
    "    \"\"\"Pierwiastek X² - sX + q = 0 bliższy liczbie cel.\"\"\"\n",
    "    r = sp.sqrt(s**2 - 4 * q)\n",
    "    return min(((s + r) / 2, (s - r) / 2), key=lambda t: abs(sp.N(t) - cel))\n",
    "\n",
    "\n",
    "eta0 = pierwiastek(-1, -4, wartosc(eta[0]))\n",
    "eta1 = -1 - eta0\n",
    "lam0 = pierwiastek(eta0, -1, wartosc(lam[0]))\n",
    "lam1 = pierwiastek(eta1, -1, wartosc(lam[1]))\n",
    "mu0 = pierwiastek(lam0, lam1, wartosc(mu[0]))\n",
    "cos17 = sp.expand(mu0 / 2)\n",
    "print(\"cos(2π/17) =\", cos17)\n",
    "print(\"liczba pierwiastków kwadratowych w wyrażeniu:\",\n",
    "      sum(1 for w in sp.preorder_traversal(cos17)\n",
    "          if isinstance(w, sp.Pow) and w.exp == sp.Rational(1, 2)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f5bbfe04",
   "metadata": {},
   "source": [
    "We check the result exactly: the minimal polynomial of the expression must equal $\\Psi_{17}$. For comparison,\n",
    "let us also take the textbook formula,\n",
    "\n",
    "$$\n",
    "16\\cos\\tfrac{2\\pi}{17}=-1+\\sqrt{17}+\\sqrt{34-2\\sqrt{17}}\n",
    "+2\\sqrt{17+3\\sqrt{17}-\\sqrt{34-2\\sqrt{17}}-2\\sqrt{34+2\\sqrt{17}}}.\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8c6bb349",
   "metadata": {},
   "outputs": [],
   "source": [
    "r17 = sp.sqrt(17)\n",
    "podrecznik = (-1 + r17 + sp.sqrt(34 - 2 * r17)\n",
    "              + 2 * sp.sqrt(17 + 3 * r17 - sp.sqrt(34 - 2 * r17)\n",
    "                            - 2 * sp.sqrt(34 + 2 * r17))) / 16\n",
    "\n",
    "for nazwa, w in ((\"nasza konstrukcja\", cos17),\n",
    "                 (\"wzór z podręcznika\", podrecznik)):\n",
    "    mp = sp.Poly(sp.minimal_polynomial(w, x), x).monic()\n",
    "    blisko = abs(sp.N(w - sp.cos(2 * sp.pi / 17), 60)) < sp.Float(\"1e-40\")\n",
    "    print(f\"{nazwa:20} wielomian minimalny = Ψ_17: {mp == Psi(17)};\",\n",
    "          f\"|różnica z cos(2π/17)| < 10⁻⁴⁰: {blisko}\")\n",
    "print(\"Ψ_17 =\", Psi(17).as_expr())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "97945ed2",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "for w in (cos17, podrecznik):\n",
    "    assert sp.Poly(sp.minimal_polynomial(w, x), x).monic() == Psi(17)\n",
    "    assert abs(sp.N(w - sp.cos(2 * sp.pi / 17), 60)) < 1e-50"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee3a56ff",
   "metadata": {},
   "source": [
    "The minimal polynomial and agreement to 40 digits are two independent checks: the first says that the expression\n",
    "is one of the eight roots of $\\Psi_{17}$, the second — which one. Square roots of constructible numbers\n",
    "can be constructed with compass and straightedge, so the regular 17-gon is constructible.\n",
    "\n",
    "## When it is impossible: the heptagon\n",
    "\n",
    "Not every regular polygon can be built this way. Let us look at the minimal polynomials for\n",
    "$n=7$ and $n=9$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "51b31afb",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Ψ_7 =\", Psi(7).as_expr(), \"  stopień\", Psi(7).degree())\n",
    "print(\"Ψ_9 =\", Psi(9).as_expr(), \"  stopień\", Psi(9).degree())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a87cdcaf",
   "metadata": {},
   "source": [
    "A number obtained from the rationals by arithmetic operations and square roots has a minimal polynomial\n",
    "of degree $2^k$ (each square root at most doubles the degree of the field extension).\n",
    "$\\Psi_7$ and $\\Psi_9$ have degree $3$, so the regular heptagon and the regular nonagon cannot be\n",
    "constructed with compass and straightedge (Wantzel, 1837; the nonagon amounts to trisecting the angle $120^\\circ$, see\n",
    "Lecture 6, §6.4). In the other direction, Gauss’s construction\n",
    "works: when $\\varphi(n)$ is a power of two, the group $(\\mathbb{Z}/n)^\\times$ has a chain of subgroups\n",
    "of index $2$, and the periods descend through quadratic equations just as for $17$. The degree of $\\Psi_n$\n",
    "therefore decides constructibility:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e93facf4",
   "metadata": {},
   "outputs": [],
   "source": [
    "konstruowalne = [n for n in range(3, 101)\n",
    "                 if Psi(n).degree() & (Psi(n).degree() - 1) == 0]\n",
    "print(\"n-kąt foremny konstruowalny, 3 ≤ n ≤ 100:\", konstruowalne)\n",
    "print(\"zgodne z warunkiem „φ(n) jest potęgą 2”:\",\n",
    "      konstruowalne == [n for n in range(3, 101)\n",
    "                        if sp.totient(n) & (sp.totient(n) - 1) == 0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "79c6cddc",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert konstruowalne == [n for n in range(3, 101)\n",
    "                         if sp.totient(n) & (sp.totient(n) - 1) == 0]\n",
    "assert {3, 5, 15, 17} <= set(konstruowalne) and not {7, 9} & set(konstruowalne)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e05389ad",
   "metadata": {},
   "source": [
    "The list consists of exactly the numbers of the form $2^k\\cdot p_1\\cdots p_r$, where the $p_i$ are distinct\n",
    "Fermat primes $3,5,17,257,65537$ (the Gauss–Wantzel theorem).\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Find $\\cos\\frac{2\\pi}{20}$ as a product of points of order $4$ and $5$, and check the minimal\n",
    "   polynomial.\n",
    "2. Build a formula for $\\cos\\frac{2\\pi}{51}$ from points of order $3$ and $17$. How many square roots\n",
    "   does the result contain?\n",
    "3. Carry the construction of periods over to $p=257$ (generator $3$). How many quadratic equations do you\n",
    "   need to solve? Which computations become expensive?\n",
    "4. For $p=7$, periods of length $2$ also exist, but the chain of subgroups of $(\\mathbb{Z}/7)^\\times$\n",
    "   has index $3$. Compute the sum, the product, and the sum of pairwise products of the three periods, and write down\n",
    "   the cubic equation for $2\\cos\\frac{2\\pi}{7}$.\n",
    "\n",
    "## Literature and further reading\n",
    "\n",
    "* C. F. Gauss, *Disquisitiones arithmeticae*, 1801, Section VII — periods and the division of the circle; English\n",
    "  translation by A. A. Clarke (Springer, 1986).\n",
    "* P. L. Wantzel, *Recherches sur les moyens de reconnaître si un Problème de Géométrie peut se résoudre\n",
    "  avec la règle et le compas*, Journal de Mathématiques Pures et Appliquées 2 (1837), 366–372\n",
    "  ([Numdam](https://www.numdam.org/item/JMPA_1837_1_2__366_0/)).\n",
    "* Euclid, *Elements*, Book IV, Proposition 16 — the 15-gon from the triangle and the pentagon\n",
    "  ([D. E. Joyce’s edition](https://mathcs.clarku.edu/~djoyce/java/elements/bookIV/propIV16.html)).\n",
    "* D. A. Cox, *Galois Theory*, 2nd ed., Wiley, 2012 ([DOI](https://doi.org/10.1002/9781118218457)) —\n",
    "  Gaussian periods, cyclotomic extensions, and geometric constructions with complete proofs.\n",
    "* I. Niven, *Irrational Numbers*, Carus Mathematical Monographs 11, MAA, 1956 — the theorem on rational\n",
    "  values of trigonometric functions ([Niven’s theorem](https://en.wikipedia.org/wiki/Niven%27s_theorem)).\n",
    "* Wikipedia entries: [Gaussian period](https://en.wikipedia.org/wiki/Gaussian_period),\n",
    "  [constructible polygon](https://en.wikipedia.org/wiki/Constructible_polygon),\n",
    "  [heptadecagon](https://en.wikipedia.org/wiki/Heptadecagon) (with an animation of the construction)."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
