{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "b768b88e",
   "metadata": {},
   "source": [
    "# Part 4. The same group elsewhere: starting points\n",
    "\n",
    "The proofs in Parts 1 and 2 did not use real numbers: they were identities of polynomials\n",
    "with integer coefficients and certificates from the equation of the circle. That is why they work wherever\n",
    "we can add and multiply. In this part we take the circle group to three places: over a finite field,\n",
    "onto the hyperbola (Pell’s equation), and into the primality test for Mersenne numbers. Each example is short\n",
    "and serves as a starting point for further work."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "78933fb1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "import sympy as sp\n",
    "\n",
    "a, b = sp.symbols(\"a b\")\n",
    "\n",
    "\n",
    "def m(P, Q, D=-1, p=None):\n",
    "    \"\"\"Prawo grupowe na krzywej x² - D·y² = 1 (okrąg: D = -1), ew. mod p.\"\"\"\n",
    "    a, b = P\n",
    "    c, d = Q\n",
    "    wynik = (a * c + D * b * d, a * d + b * c)\n",
    "    return wynik if p is None else (wynik[0] % p, wynik[1] % p)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0c130a08",
   "metadata": {},
   "source": [
    "## The circle over a finite field\n",
    "\n",
    "Over $\\mathbb{F}_p$ the circle $a^2+b^2=1$ is a finite set, and the group law is the same formula\n",
    "computed modulo $p$. Let us count the points and find the largest order of an element."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "44f7e160",
   "metadata": {},
   "outputs": [],
   "source": [
    "def punkty_okregu(p):\n",
    "    return [(u, v) for u in range(p) for v in range(p)\n",
    "            if (u * u + v * v) % p == 1]\n",
    "\n",
    "\n",
    "def rzad(P, p):\n",
    "    Q, k = P, 1\n",
    "    while Q != (1, 0):\n",
    "        Q, k = m(Q, P, p=p), k + 1\n",
    "    return k\n",
    "\n",
    "\n",
    "print(f\"{'p':>3} {'p mod 4':>8} {'punktów':>8} {'największy rząd':>16}\")\n",
    "wiersze = []\n",
    "for p in sp.primerange(3, 60):\n",
    "    pkt = punkty_okregu(p)\n",
    "    wiersze.append((p, p % 4, len(pkt), max(rzad(P, p) for P in pkt)))\n",
    "    print(f\"{p:>3} {p % 4:>8} {len(pkt):>8} {wiersze[-1][3]:>16}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f64add40",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert all(n == (p - 1 if r == 1 else p + 1) and n == mx\n",
    "           for p, r, n, mx in wiersze)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0ac61a91",
   "metadata": {},
   "source": [
    "The pattern is clear: there are $p-1$ points when $p\\equiv1\\pmod4$ and $p+1$ when\n",
    "$p\\equiv3\\pmod4$, and the largest order equals the number of points, so the group is **cyclic**.\n",
    "The explanation: when $-1=i^2$ has a square root in $\\mathbb{F}_p$, the map $(a,b)\\mapsto a+ib$ carries\n",
    "the circle onto the group $\\mathbb{F}_p^\\times$ (of order $p-1$); when it does not, the circle consists of the elements of norm $1$\n",
    "in the field $\\mathbb{F}_{p^2}=\\mathbb{F}_p(i)$, and there are $p+1$ of them.\n",
    "\n",
    "**Further:** this is the simplest example of an **algebraic torus**. The point counts $p\\mp1$ are\n",
    "the prototype of Hasse’s theorem for elliptic curves, where the number of points is $p+1-t$\n",
    "with $|t|\\le2\\sqrt p$.\n",
    "\n",
    "## The hyperbola and Pell’s equation\n",
    "\n",
    "Let us replace the circle by the hyperbola $x^2-Dy^2=1$ with $D>0$ not a square. The group law\n",
    "$m\\bigl((a,b),(c,d)\\bigr)=(ac+Dbd,\\ ad+bc)$ is multiplication of numbers $a+b\\sqrt D$. The computation from Part 1\n",
    "carries over unchanged:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4bb9e3a2",
   "metadata": {},
   "outputs": [],
   "source": [
    "c, d, D = sp.symbols(\"c d D\")\n",
    "x, y = m((a, b), (c, d), D=D)\n",
    "print(sp.factor(x**2 - D * y**2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "23d860db",
   "metadata": {},
   "source": [
    "Moreover, the powers are described by **the same Chebyshev polynomials**. On the hyperbola $Db^2=a^2-1$, so\n",
    "we replace $b^2$ by $(a^2-1)/D$, and the induction step from Part 2 looks like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3f9fc1f8",
   "metadata": {},
   "outputs": [],
   "source": [
    "T, U = sp.symbols(\"T U\")\n",
    "krok = m((T, b * U), (a, b), D=D)\n",
    "nastepny = (a * T - (1 - a**2) * U, b * (T + a * U))   # rekurencja z części 2\n",
    "podstaw = {b**2: (a**2 - 1) / D}\n",
    "print([sp.simplify(sp.expand(krok[i] - nastepny[i]).subs(podstaw))\n",
    "       for i in range(2)])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6507b5c8",
   "metadata": {},
   "source": [
    "Hence if $(x_1,y_1)$ is the smallest solution of Pell’s equation, the subsequent solutions are\n",
    "$\\bigl(T_n(x_1),\\ y_1U_{n-1}(x_1)\\bigr)$. For $D=2$ we start from $(3,2)$, and for the famous example\n",
    "$D=61$ from $(1766319049,\\ 226153980)$; this solution was already known to the Indian mathematician Bhaskara II\n",
    "in the 12th century."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0700e242",
   "metadata": {},
   "outputs": [],
   "source": [
    "for D_, (x1, y1) in ((2, (3, 2)), (61, (1766319049, 226153980))):\n",
    "    rozw = [(sp.chebyshevt(n, x1), y1 * sp.chebyshevu(n - 1, x1))\n",
    "            for n in range(1, 6)]\n",
    "    print(f\"D = {D_}: rozwiązania poprawne:\",\n",
    "          all(u * u - D_ * v * v == 1 for u, v in rozw))\n",
    "    for n, (u, v) in enumerate(rozw[:3], 1):\n",
    "        print(f\"   n = {n}: x = {u}, y = {v}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3640a6ec",
   "metadata": {},
   "source": [
    "**Further:** the smallest solution is found by the continued fraction algorithm for $\\sqrt D$\n",
    "(the function `diop_DN` in the module `sympy.solvers.diophantine.diophantine`). The group of solutions is infinite cyclic up\n",
    "to sign — this is Dirichlet’s unit theorem in its simplest case.\n",
    "\n",
    "## The Lucas–Lehmer test\n",
    "\n",
    "The point $(2,1)$ lies on the hyperbola $x^2-3y^2=1$. Its $2^k$th powers have first coordinates\n",
    "$T_{2^k}(2)$, and from the composition $T_{2^{k+1}}=T_2\\circ T_{2^k}$ and $T_2(x)=2x^2-1$ it follows that the numbers\n",
    "$s_k=2\\,T_{2^k}(2)$ satisfy\n",
    "\n",
    "$$\n",
    "s_0=4,\\qquad s_{k+1}=s_k^2-2.\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "10e47dbe",
   "metadata": {},
   "outputs": [],
   "source": [
    "s_k = 4\n",
    "for k in range(5):\n",
    "    print(k, s_k, s_k == 2 * sp.chebyshevt(2**k, 2))\n",
    "    s_k = s_k**2 - 2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "158e2f10",
   "metadata": {},
   "source": [
    "**The Lucas–Lehmer test** (Lucas 1878, Lehmer 1930): for an odd prime $q$, the number $M_q=2^q-1$ is prime\n",
    "if and only if $s_{q-2}\\equiv0\\pmod{M_q}$. Behind the proof is exactly our group: the point\n",
    "$(2,1)$ on the hyperbola $x^2-3y^2=1$ over $\\mathbb{F}_{M_q}$ (or over its degree-2 extension)\n",
    "and its order."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c1666c27",
   "metadata": {},
   "outputs": [],
   "source": [
    "def lucas_lehmer(q):\n",
    "    M, s = 2**q - 1, 4\n",
    "    for _ in range(q - 2):\n",
    "        s = (s * s - 2) % M\n",
    "    return s == 0\n",
    "\n",
    "\n",
    "start = time.perf_counter()\n",
    "wykladniki = [q for q in sp.primerange(3, 1300) if lucas_lehmer(q)]\n",
    "czas = time.perf_counter() - start\n",
    "print(\"q < 1300 z pierwszą M_q:\", wykladniki)\n",
    "print(f\"czas: {czas:.2f} s;  M_1279 ma {len(str(2**1279 - 1))} cyfr\")\n",
    "print(\"zgodne z isprime dla q < 130:\",\n",
    "      [q for q in wykladniki if q < 130]\n",
    "      == [q for q in sp.primerange(3, 130) if sp.isprime(2**q - 1)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bb792fd5",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert wykladniki == [3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127,\n",
    "                      521, 607, 1279]\n",
    "assert czas < 1 and len(str(2**1279 - 1)) == 386"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c47c047",
   "metadata": {},
   "source": [
    "$M_{1279}$ has $386$ digits, and testing all $q<1300$ together takes a fraction of a second: for $q=1279$\n",
    "it is only $1277$ squarings modulo $M_q$. The largest known primes are Mersenne\n",
    "numbers, and their primality is confirmed by tests based on the same idea.\n",
    "\n",
    "**Further:** a full proof of the test (it requires the order of the point $(2,1)$ in the group over $\\mathbb{F}_{M_q}$ or\n",
    "$\\mathbb{F}_{M_q^2}$); Lucas tests for numbers of other forms; exponentiation in a group as a general\n",
    "scheme for primality tests.\n",
    "\n",
    "## Elliptic curves\n",
    "\n",
    "The next algebraic group after the circle and the hyperbola is an elliptic curve $y^2=x^3+Ax+B$ with the\n",
    "chord-and-tangent law. Closure and commutativity are checked as in Part 1, but **associativity**\n",
    "is already a large symbolic computation and a good test of what a computer algebra system can do.\n",
    "\n",
    "Part 5 shows what all these examples have in common: each one is an algebraic group of dimension 1,\n",
    "and for the circle and the hyperbola the most important properties follow from the Lie algebra and the\n",
    "exponential map. For elliptic curves the Lie algebra says much less, and the rest has to be found in arithmetic.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Check for $p<200$ that the circle $a^2+b^2=1$ over $\\mathbb{F}_p$ has $p-\\left(\\frac{-1}{p}\\right)$\n",
    "   points, and find a generator for $p=13$ and $p=19$.\n",
    "2. Find the smallest solution of $x^2-13y^2=1$ (searching is allowed) and list the next three\n",
    "   using Chebyshev polynomials.\n",
    "3. Show that the Lucas–Lehmer test can be written as exponentiation of the point $(2,1)$ in the group\n",
    "   $x^2-3y^2=1$ modulo $M_q$, and check this for $q=7$.\n",
    "4. The curve $x^2+xy+y^2=1$ is also a group (norms in $\\mathbb{Q}(\\sqrt{-3})$). Derive its group\n",
    "   law and check it symbolically.\n",
    "\n",
    "## Literature and further reading\n",
    "\n",
    "* F. Lemmermeyer, *Conics — a Poor Man's Elliptic Curves*,\n",
    "  [arXiv:math/0311306](https://arxiv.org/abs/math/0311306) — the circle and other conics over $\\mathbb{F}_p$\n",
    "  as groups, with analogies to elliptic curves.\n",
    "* H. W. Lenstra Jr., *Solving the Pell Equation*, Notices of the AMS 49 (2002), 182–192\n",
    "  ([PDF](https://www.ams.org/notices/200202/fea-lenstra.pdf)) — history, algorithms, and complexity;\n",
    "  [Pell’s equation](https://en.wikipedia.org/wiki/Pell%27s_equation) on Wikipedia.\n",
    "* D. H. Lehmer, *An Extended Theory of Lucas' Functions*, Annals of Mathematics 31 (1930), 419–448\n",
    "  ([DOI](https://doi.org/10.2307/1968235)); R. Crandall, C. Pomerance, *Prime Numbers:\n",
    "  A Computational Perspective*, 2nd ed., Springer, 2005 ([DOI](https://doi.org/10.1007/0-387-28979-8));\n",
    "  [Lucas–Lehmer test](https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test);\n",
    "  [GIMPS](https://www.mersenne.org/) — the project searching for Mersenne primes.\n",
    "* J. H. Silverman, *The Arithmetic of Elliptic Curves*, 2nd ed., Springer, 2009\n",
    "  ([DOI](https://doi.org/10.1007/978-0-387-09494-6)) — the group law, points over $\\mathbb{F}_p$,\n",
    "  and [Hasse’s theorem](https://en.wikipedia.org/wiki/Hasse%27s_theorem_on_elliptic_curves)."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
