{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c000",
   "metadata": {},
   "source": [
    "# Lab 2: SymPy and SageMath — first symbolic computations\n",
    "\n",
    "**Duration:** 90 min · **Lecture:** {doc}`How does a computer algebra system work? <../wyklady/w01_3_jak_dziala_cas>`\n",
    "\n",
    "## Learning goals\n",
    "\n",
    "After this session you will be able to:\n",
    "\n",
    "1. create symbols and expressions in **SymPy** and distinguish **exact** numbers (`Integer`, `Rational`, `sqrt(2)`, `pi`) from **approximate** ones (`Float`);\n",
    "2. transform expressions (`expand`, `factor`, `simplify`, `cancel`, `apart`, `together`, `collect`), substitute (`subs`), and solve equations (`solve`, `solveset`);\n",
    "3. look “under the hood” of a computer algebra system (CAS): see the **expression tree** (`srepr`, `.func`, `.args`);\n",
    "4. control the precision of computations (`N`) and understand the role of **assumptions** (`real=True`, `positive=True`);\n",
    "5. compare the syntax of **SymPy** and **SageMath**;\n",
    "6. work through one example in three worlds: **numerical**, **symbolic**, and **formal** (a proof in Peano Lab).\n",
    "\n",
    "```{admonition} Preparation\n",
    ":class: tip\n",
    "We use the environment from Lab 1 (`.venv` with the `sympy` package). Convention: `import sympy as sp` — this way it is immediately clear which functions come from SymPy. We avoid `from sympy import *`, because it brings in, among others, the single-letter names `N`, `S`, `E`, and `I`, which are easy to overwrite accidentally with a variable of your own (in B6 we name an integral `I` ourselves).\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c001",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sympy as sp\n",
    "print(\"SymPy\", sp.__version__)\n",
    "x, y, z = sp.symbols('x y z')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c002",
   "metadata": {},
   "source": [
    "## Part A — warm-up (≈ 25 min)\n",
    "\n",
    "### A1. Symbols and expressions ★\n",
    "\n",
    "The function `sp.symbols('x y z')` in the cell above created three **symbols**, i.e., SymPy objects that stand for mathematical variables (as opposed to Python variables that store numbers). Operations on symbols produce **expressions**, and the notebook displays the value of the last expression in a cell as a mathematical formula:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c003",
   "metadata": {},
   "outputs": [],
   "source": [
    "e = (x + y)**3\n",
    "e"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c004",
   "metadata": {},
   "source": [
    "The expression `e` stays in the form in which we entered it: SymPy does not multiply out parentheses\n",
    "on its own, because it cannot know which form we need. Expansion and factorization are performed\n",
    "on request:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c005",
   "metadata": {},
   "outputs": [],
   "source": [
    "sp.expand(e)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c006",
   "metadata": {},
   "outputs": [],
   "source": [
    "sp.factor(x**4 - 1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c007",
   "metadata": {},
   "source": [
    "**Exercise.** Expand $(x + y + z)^3$. How many terms does the result have? (*Hint:* `len(wyrazenie.args)`.) Compare the answer with the number of monomials of degree $3$ in three variables, which equals $\\binom{3+2}{2}$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c008",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c009",
   "metadata": {},
   "source": [
    "### A2. Exact and approximate numbers ★\n",
    "\n",
    "Numbers in SymPy are either **exact** (integers, rationals, roots, constants such as $\\pi$)\n",
    "or **approximate** (`Float`). The biggest pitfall lurks at the interface with Python: a fraction written with\n",
    "the ordinary `/` on integers is computed by Python before SymPy ever sees it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c010",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(1/3, type(1/3))                  # to oblicza Python: float!\n",
    "print(sp.Rational(1, 3), sp.S(1)/3)    # liczby wymierne SymPy\n",
    "print(x + 1/3)                         # pułapka: 1/3 policzył Python, zanim SymPy zobaczył ułamek\n",
    "print(x + sp.Rational(1, 3))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c011",
   "metadata": {},
   "source": [
    "Exact numbers behave just as they do in mathematics — irrational and complex ones included:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c012",
   "metadata": {},
   "outputs": [],
   "source": [
    "sp.sqrt(8), sp.sqrt(2)**2, sp.pi, sp.E, sp.I**2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c013",
   "metadata": {},
   "source": [
    "SymPy immediately turns $\\sqrt{8}$ into $2\\sqrt{2}$, and $(\\sqrt{2})^2$ into $2$ — this is **automatic simplification**, performed as soon as the expression is created. Approximate values, with any number of digits, are obtained with the function `sp.N` (or the method `.evalf()`):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c014",
   "metadata": {},
   "outputs": [],
   "source": [
    "sp.N(sp.sqrt(2), 50)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c015",
   "metadata": {},
   "source": [
    "The function `sp.nsimplify` tries to guess the exact value of an approximate number — this is a **heuristic**, not a proof:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c016",
   "metadata": {},
   "outputs": [],
   "source": [
    "sp.nsimplify(0.333333333333333), sp.nsimplify(1.618033988749895, [sp.sqrt(5)])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c017",
   "metadata": {},
   "source": [
    "**Exercise.** Compute $\\pi$ to $100$ decimal places. What is the hundredth digit after the decimal point? Note: `sp.N` rounds the last digit it prints. Compare the hundredth digit read off from `sp.N(sp.pi, 101)` and from `sp.N(sp.pi, 110)`, and explain the difference."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c018",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c019",
   "metadata": {},
   "source": [
    "### A3. Transforming expressions ★\n",
    "\n",
    "| Function | What it does | Example |\n",
    "|---|---|---|\n",
    "| `sp.expand` | multiplies out parentheses | $(x+1)^2 \\to x^2 + 2x + 1$ |\n",
    "| `sp.factor` | factors (over $\\mathbb{Q}$ by default) | $x^4 - 1 \\to (x-1)(x+1)(x^2+1)$ |\n",
    "| `sp.cancel` | cancels common factors in a rational function | $\\frac{x^2-1}{x-1} \\to x + 1$ |\n",
    "| `sp.apart` | decomposes into partial fractions | $\\frac{1}{x(x+1)} \\to \\frac{1}{x} - \\frac{1}{x+1}$ |\n",
    "| `sp.together` | combines over a common denominator | the inverse of `apart` |\n",
    "| `sp.collect` | collects terms with respect to powers of a variable | $x^2 + xy + x \\to x^2 + x(y + 1)$ |\n",
    "| `sp.simplify` | tries many methods and picks the “simplest” result | $\\sin^2 x + \\cos^2 x \\to 1$ |"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c020",
   "metadata": {},
   "outputs": [],
   "source": [
    "sp.cancel((x**2 - 1)/(x - 1))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c021",
   "metadata": {},
   "source": [
    "```{warning}\n",
    "`cancel` returns $x + 1$, even though the expression $\\frac{x^2-1}{x-1}$ is **undefined** at $x = 1$. A CAS treats it as an element of the field of rational functions $\\mathbb{Q}(x)$, not as a function on a specific domain. This is one of the challenges in designing computer algebra systems that we discussed in the lecture.\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c022",
   "metadata": {},
   "outputs": [],
   "source": [
    "sp.apart(1/(x*(x + 1))), sp.together(1/x - 1/(x + 1))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c023",
   "metadata": {},
   "source": [
    "The functions `apart` and `together` work in opposite directions: the first decomposes a rational function\n",
    "into partial fractions, the second combines a sum of fractions over a common denominator. Composing the two\n",
    "gives the same rational function, but not necessarily the same written form. The function `collect` arranges\n",
    "an expression by powers of a chosen variable — below, we treat the expression as a polynomial in the variable $x$\n",
    "with coefficients depending on $y$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c024",
   "metadata": {},
   "outputs": [],
   "source": [
    "sp.collect(sp.expand((x + y + 1)**2), x)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c025",
   "metadata": {},
   "source": [
    "The function `simplify` recognizes the Pythagorean trigonometric identity, and trigonometric transformations work\n",
    "in both directions: `expand_trig` expands trigonometric functions of sums and multiples of an angle, and `trigsimp` tries to collapse the expression back:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c026",
   "metadata": {},
   "outputs": [],
   "source": [
    "sp.simplify(sp.sin(x)**2 + sp.cos(x)**2), sp.expand_trig(sp.sin(2*x)), sp.trigsimp(2*sp.sin(x)*sp.cos(x))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c027",
   "metadata": {},
   "source": [
    "The result of factorization depends on the field of coefficients. Over $\\mathbb{Q}$, the polynomial $x^2 - 2$ is\n",
    "irreducible; after adjoining $\\sqrt2$ (the `extension` option), it splits into linear factors,\n",
    "and the option `gaussian=True` allows coefficients from $\\mathbb{Q}(i)$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c028",
   "metadata": {},
   "outputs": [],
   "source": [
    "sp.factor(x**2 - 2), sp.factor(x**2 - 2, extension=sp.sqrt(2)), sp.factor(x**4 - 1, gaussian=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c029",
   "metadata": {},
   "source": [
    "**Exercise.** (a) Factor $x^6 - 1$ over $\\mathbb{Q}$. (b) Decompose $\\dfrac{1}{x^4 - 1}$ into partial fractions. (c) Simplify $\\dfrac{x^3 - 1}{x^2 - 1}$ by canceling common factors. (d) Factor $x^4 + 4$ over $\\mathbb{Q}$ (the Sophie Germain identity!)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c030",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c031",
   "metadata": {},
   "source": [
    "### A4. The expression tree: how SymPy stores formulas ★\n",
    "\n",
    "The function `srepr` shows the full structure of an expression, and the attributes `func` and `args` show the root of the tree\n",
    "(the kind of operation) and its subtrees:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c032",
   "metadata": {},
   "outputs": [],
   "source": [
    "e = x**2 + 2*x + 1\n",
    "print(sp.srepr(e))\n",
    "print(e.func, e.args)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c033",
   "metadata": {},
   "source": [
    "The tuple `e.args` begins with the constant $1$, even though we typed it last: SymPy stores the arguments\n",
    "of a sum in an order of its own choosing. (The function `srepr`, like ordinary printing, arranges\n",
    "the terms by decreasing powers, which is why, in the first line, the order looks like the one we typed.)\n",
    "Subtraction and division do not have nodes of their own:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c034",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(sp.srepr(x - y))    # nie ma osobnego węzła „odejmowanie”...\n",
    "print(sp.srepr(x / y))    # ...ani „dzielenie”"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c035",
   "metadata": {},
   "source": [
    "Internally, $x - y$ is `Add(x, Mul(-1, y))`, and $x/y$ is `Mul(x, Pow(y, -1))`. The arguments of sums and products are stored in a fixed order, so `x + y` and `y + x` have **the same** tree, and the comparison `x + y == y + x` gives `True`. This normalization allows expressions that are equal “up to commutativity” to be recognized quickly, but it is not a canonical form in the sense of the lecture: $(x+1)^2$ and $x^2 + 2x + 1$ have different trees, even though they denote the same polynomial. You can explore expression trees in the <a href=\"../../applets/expression-tree.html\" target=\"_blank\">“Expression tree” applet</a>.\n",
    "\n",
    "The function `sp.preorder_traversal` traverses the tree in preorder (first the node, then each of its subtrees in turn). Let us print the type and content of every node of the tree of $x^2 + 2x + 1$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c036",
   "metadata": {},
   "outputs": [],
   "source": [
    "for w in sp.preorder_traversal(e):\n",
    "    print(type(w).__name__, \"\\t\", w)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c037",
   "metadata": {},
   "source": [
    "The tree has $8$ nodes. The number $2$ occurs in it twice as a separate leaf (the exponent and the coefficient), and the constant $1$ has its own class `One`: SymPy stores the most common constants as unique instances (*singletons*).\n",
    "\n",
    "**Exercise.** Draw the expression tree of $\\sin^2 x + \\cos^2 x$ on paper and compare it with the output of `sp.srepr`. How many nodes does this tree have? Count them with a program as well."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c038",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c039",
   "metadata": {},
   "source": [
    "### A5. Substitution and equations ★\n",
    "\n",
    "The method `subs` substitutes numbers or other expressions for symbols; with a dictionary, several values\n",
    "can be substituted at once:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c040",
   "metadata": {},
   "outputs": [],
   "source": [
    "e = x**2 + y\n",
    "e.subs(x, 3), e.subs({x: 1, y: 2})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c041",
   "metadata": {},
   "source": [
    "The function `solve` solves algebraic equations and returns a list of solutions, in this case exact ones.\n",
    "An expression given without an equals sign is set equal to zero:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c042",
   "metadata": {},
   "outputs": [],
   "source": [
    "sp.solve(x**2 - x - 1, x)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c043",
   "metadata": {},
   "source": [
    "The equation $\\sin x = \\tfrac12$ has infinitely many real solutions. No list can hold\n",
    "them all, so we use the function `solveset`, which returns a **set** — here\n",
    "$\\{\\tfrac{\\pi}{6} + 2k\\pi : k \\in \\mathbb{Z}\\} \\cup \\{\\tfrac{5\\pi}{6} + 2k\\pi : k \\in \\mathbb{Z}\\}$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c044",
   "metadata": {},
   "outputs": [],
   "source": [
    "sp.solveset(sp.sin(x) - sp.Rational(1, 2), x, domain=sp.S.Reals)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c045",
   "metadata": {},
   "source": [
    "The notation `ImageSet(Lambda(_n, 2*_n*pi + pi/6), Integers)` denotes the image of the set $\\mathbb{Z}$ under the function $n \\mapsto 2n\\pi + \\frac{\\pi}{6}$, i.e., the first of the two sets given above.\n",
    "\n",
    "A system of equations is given as a list of expressions (each set equal to zero) and a list of unknowns:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c046",
   "metadata": {},
   "outputs": [],
   "source": [
    "sp.solve([x + y - 3, x - y - 1], [x, y])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c047",
   "metadata": {},
   "source": [
    "**Exercise.** Solve the equation $x^3 - 6x^2 + 11x - 6 = 0$ and check, by substituting the numbers obtained into the polynomial, that they are roots. Also solve the equation $x^3 = 2$ with `sp.solve` and with `sp.solveset(..., domain=sp.S.Reals)`. How do the results differ?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c048",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c049",
   "metadata": {},
   "source": [
    "### A6. Assumptions: $\\sqrt{x^2}$ is not always $x$ ★\n",
    "\n",
    "SymPy treats a symbol without assumptions as an arbitrary complex number. Assumptions (real,\n",
    "positive, integer, …) are given when the symbol is created, and they determine which simplifications are\n",
    "allowed:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c050",
   "metadata": {},
   "outputs": [],
   "source": [
    "t = sp.Symbol('t')                       # domyślnie: dowolna liczba zespolona\n",
    "t_r = sp.Symbol('t', real=True)\n",
    "t_p = sp.Symbol('t', positive=True)\n",
    "sp.sqrt(t**2), sp.sqrt(t_r**2), sp.sqrt(t_p**2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c051",
   "metadata": {},
   "source": [
    "The result depends on the assumptions. For $t > 0$ we have $\\sqrt{t^2} = t$. For real $t$ the correct formula is $\\sqrt{t^2} = |t|$ (e.g., for $t = -1$ we have $\\sqrt{t^2} = 1 \\ne t$), hence `Abs(t)`. For complex $t$ the square root denotes the **principal branch**, so $\\sqrt{t^2}$ equals $t$ or $-t$, depending on where $t$ lies in the complex plane; there is no simple formula, which is why SymPy does not simplify $\\sqrt{t^2}$ without assumptions. A CAS that “simplified” too boldly would give wrong results.\n",
    "\n",
    "**Exercise.** Check what SymPy does with the expressions $\\ln(e^{t})$ and $(\\sqrt{t})^2$ (compare them with $(t^2)^{1/2} = \\sqrt{t^2}$ from the example above) for a symbol without assumptions, with `real=True`, and with `positive=True`. Explain the differences."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c052",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c053",
   "metadata": {},
   "source": [
    "### A7. SymPy vs. SageMath ★\n",
    "\n",
    "**SageMath** is a system built on Python that brings many specialized libraries (including PARI/GP, FLINT, Maxima, Singular, and GAP) together under a common interface. **SymPy** is a library written in pure Python — it installs with a single command, `pip install sympy`. Sage is not installed in our `.venv` environment; the easiest way to try it is in the browser: **SageMathCell** <https://sagecell.sagemath.org> or **CoCalc** <https://cocalc.com>.\n",
    "\n",
    "| Task | SymPy | SageMath |\n",
    "|---|---|---|\n",
    "| symbols | `x, y = sp.symbols('x y')` | `x, y = var('x y')` (the symbol `x` is predefined) |\n",
    "| power | `x**3` | `x^3` or `x**3` |\n",
    "| the number $\\frac12$ | `sp.Rational(1, 2)` (because `1/2` is the `float` number `0.5`!) | `1/2` (a rational number) |\n",
    "| expansion, factorization | `sp.expand(e)`, `sp.factor(e)` | `e.expand()`, `factor(e)` |\n",
    "| polynomial ring | `R = sp.QQ[x]` (a polynomial in it: `sp.Poly(x**4 - 1, x, domain='QQ')`) | `R.<x> = QQ[]` |\n",
    "| equations | `sp.solve(x**2 - 2, x)` | `solve(x^2 - 2, x)` |\n",
    "| approximation | `sp.N(sp.pi, 50)` | `pi.n(digits=50)` |\n",
    "| Fibonacci numbers | `sp.fibonacci(10)` | `fibonacci(10)` |\n",
    "| matrix, determinant | `sp.Matrix([[1, 2], [3, 4]]).det()` | `matrix(QQ, [[1, 2], [3, 4]]).det()` |\n",
    "| definite integral | `sp.integrate(sp.sin(x), (x, 0, sp.pi))` | `integrate(sin(x), x, 0, pi)` |\n",
    "\n",
    "Before running code, Sage **preprocesses** it (*preparsing*): it replaces `^` with `**`, integer literals with `Integer` objects (which is why `1/2` is a fraction and not a `float`), and the notation `R.<t> = QQ[]` with ordinary function calls. An example (run it in SageMathCell — in plain Python this code **does not work**):\n",
    "\n",
    "```python\n",
    "# SageMath\n",
    "R.<t> = QQ[]              # pierścień wielomianów Q[t]\n",
    "f = t^4 - 1\n",
    "print(f.factor())         # rozkład nad Q\n",
    "print(1/2 + 1/3)          # 5/6 — liczba wymierna, bez float\n",
    "print(pi.n(digits=30))\n",
    "print(fibonacci(100))\n",
    "```\n",
    "\n",
    "**Exercise.** Run the code above in SageMathCell, then write its SymPy equivalent in the cell below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c054",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c055",
   "metadata": {},
   "source": [
    "## Part B — main exercises (≈ 40 min)\n",
    "\n",
    "### B1. Symbolic sums ★\n",
    "\n",
    "The function `summation` computes sums in closed form. Let us compute the sums of the first, second, and third\n",
    "powers of the numbers $1, 2, \\dots, n$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c056",
   "metadata": {},
   "outputs": [],
   "source": [
    "k = sp.symbols('k', integer=True, positive=True)\n",
    "n = sp.symbols('n', integer=True, positive=True)\n",
    "S1 = sp.summation(k, (k, 1, n))\n",
    "S2 = sp.summation(k**2, (k, 1, n))\n",
    "S3 = sp.summation(k**3, (k, 1, n))\n",
    "S1, sp.factor(S2), sp.factor(S3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c057",
   "metadata": {},
   "source": [
    "Note that $\\sum_{k=1}^n k^3 = \\left(\\sum_{k=1}^n k\\right)^2$ (Nicomachus of Gerasa).\n",
    "\n",
    "**Exercise.** (a) Verify this identity symbolically. (b) Compute $\\sum_{k=1}^n k^4$ and factor it. (c) Compute $\\sum_{k=1}^{n} (2k - 1)$, $\\sum_{j=0}^{n} \\binom{n}{j}$, and $\\sum_{j=0}^{n} q^j$. What does a result of type `Piecewise` mean?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c058",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c059",
   "metadata": {},
   "source": [
    "### B2. The last digit of $A_{1000}$ ★★\n",
    "\n",
    "For every $n \\ge 0$ there exist uniquely determined integers $A_n, B_n$ such that $(1 + \\sqrt{2})^n = A_n + B_n\\sqrt{2}$ (why do they exist, and why are they unique?).\n",
    "\n",
    "**Exercise.**\n",
    "\n",
    "(a) Find the last digit of $A_{1000}$. *Hint:* `sp.expand((1 + sp.sqrt(2))**1000)`, followed by the method `.coeff(sp.sqrt(2), 0)`. How many digits does $A_{1000}$ have?\n",
    "\n",
    "(b) Check that $A_n^2 - 2B_n^2 = (-1)^n$ for $n \\le 20$ (Pell’s equation).\n",
    "\n",
    "(c) Justify the recurrence $A_{n+1} = A_n + 2B_n$, $B_{n+1} = A_n + B_n$ and use it to compute $A_{1000} \\bmod 10$ with integers only (and remainders modulo $10$).\n",
    "\n",
    "(d) **Analysis:** print $A_n \\bmod 10$ for $n = 0, 1, \\dots, 30$. What do you notice? (This will be useful in exercise Z3 at the end of the set.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c060",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c061",
   "metadata": {},
   "source": [
    "### B3. Binet’s formula and Cassini’s identity ★★\n",
    "\n",
    "Binet’s formula: $F_n = \\dfrac{\\varphi^n - \\psi^n}{\\sqrt5}$, where $\\varphi = \\frac{1+\\sqrt5}{2}$, $\\psi = \\frac{1-\\sqrt5}{2}$. **Cassini’s identity:** $F_n^2 - F_{n+1}F_{n-1} = (-1)^{n-1}$ for $n \\ge 1$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c062",
   "metadata": {},
   "outputs": [],
   "source": [
    "phi = (1 + sp.sqrt(5)) / 2\n",
    "psi = (1 - sp.sqrt(5)) / 2\n",
    "\n",
    "def F(m):\n",
    "    return (phi**m - psi**m) / sp.sqrt(5)\n",
    "\n",
    "[sp.expand(F(m)) for m in range(11)]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c063",
   "metadata": {},
   "source": [
    "**Exercise.**\n",
    "\n",
    "(a) Check that, after expansion (`sp.expand`), the values `F(m)` agree with `sp.fibonacci(m)` for $0 \\le m \\le 30$, and that Cassini’s identity holds for $n = 1, \\dots, 30$ (using integer arithmetic).\n",
    "\n",
    "(b) Try to “prove” the identity symbolically: for the symbol `m = sp.symbols('m', integer=True)`, simplify the expression `wyr = F(m)**2 - F(m+1)*F(m-1) - (-1)**(m-1)` with `sp.simplify`. Do you get $0$?\n",
    "\n",
    "(c) Help the system: `sp.simplify(sp.powsimp(sp.expand(wyr), force=True))`. Read in the documentation (`help(sp.powsimp)`) what the option `force=True` does and why it can be dangerous. Why is it legitimate to use it here?\n",
    "\n",
    "(d) Another strategy: introduce new symbols $A = \\varphi^m$, $B = \\psi^m$ and write the left-hand side of the identity as a rational expression in $A, B$ (e.g., $\\varphi^{m+1} = \\varphi A$, $\\psi^{m-1} = B/\\psi$). Simplify it. How do you obtain $(-1)^{m-1}$ from the result $-AB$?\n",
    "\n",
    "(e) **Analysis:** which of the steps (a)–(d) are proofs, and which are only verifications?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c064",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c065",
   "metadata": {},
   "source": [
    "### B4. Vieta’s formulas ★★\n",
    "\n",
    "The numbers $\\alpha, \\beta$ are the roots of the polynomial $x^2 + mx + 1$. Express $\\dfrac{1}{\\alpha^3} + \\dfrac{1}{\\beta^3}$ as a function of the parameter $m$.\n",
    "\n",
    "**Exercise.** Solve this problem in three ways and compare the results:\n",
    "\n",
    "(a) **directly:** find the roots with `sp.solve`, compute the expression, and simplify it;\n",
    "\n",
    "(b) **Vieta’s formulas:** $\\alpha + \\beta = -m$, $\\alpha\\beta = 1$, and $\\alpha^3 + \\beta^3 = (\\alpha+\\beta)^3 - 3\\alpha\\beta(\\alpha+\\beta)$;\n",
    "\n",
    "(c) **the resultant:** the polynomial `sp.resultant(x**2 + m*x + 1, y*x**3 - 1, x)`, regarded as a polynomial in the variable $y$, has the roots $1/\\alpha^3$ and $1/\\beta^3$ — why? Read off the sum of the roots from Vieta’s formulas.\n",
    "\n",
    "(d) Check the result numerically for $m = 3$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c066",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c067",
   "metadata": {},
   "source": [
    "### B5. A number satisfying $m = \\dfrac{1}{1+m}$ ★\n",
    "\n",
    "The number $m$ is equal to the reciprocal of $m + 1$. Find $m^{10}$.\n",
    "\n",
    "**Exercise.** (a) Solve the equation and compute $m^{10}$ exactly for both solutions (`sp.expand`, `sp.radsimp`). (b) Compute the remainder of $x^{10}$ upon division by $x^2 + x - 1$: `sp.rem(x**10, x**2 + x - 1, x)`. Explain why $m^{10} = 34 - 55m$. (c) Print the remainders of $x^k$ upon division by $x^2 + x - 1$ for $k = 0, 1, \\dots, 12$. What numbers do you see? (This will be useful in exercise Z1 at the end of the set.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c068",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c069",
   "metadata": {},
   "source": [
    "### B6. Limits, derivatives, and integrals ★\n",
    "\n",
    "SymPy computes limits, derivatives, and integrals symbolically — the result is exact, provided it can be\n",
    "found at all. Two classical limits:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c070",
   "metadata": {},
   "outputs": [],
   "source": [
    "N_ = sp.symbols('N', positive=True)\n",
    "sp.limit(sp.sin(x)/x, x, 0), sp.limit((1 + 1/N_)**N_, N_, sp.oo)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c071",
   "metadata": {},
   "source": [
    "SymPy computes the derivative of a product using the formula $(fg)' = f'g + fg'$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c072",
   "metadata": {},
   "outputs": [],
   "source": [
    "sp.diff(sp.exp(x)*sp.sin(x), x)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c073",
   "metadata": {},
   "source": [
    "SymPy also computes definite integrals, improper ones included. Here they are $\\int_0^\\infty x e^{-x}\\,dx = 1$ and the Gaussian integral\n",
    "$\\int_{-\\infty}^{\\infty} e^{-x^2}\\,dx = \\sqrt{\\pi}$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c074",
   "metadata": {},
   "outputs": [],
   "source": [
    "sp.integrate(x*sp.exp(-x), (x, 0, sp.oo)), sp.integrate(sp.exp(-x**2), (x, -sp.oo, sp.oo))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c075",
   "metadata": {},
   "source": [
    "Now let us compute the indefinite integrals of two innocent-looking functions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c076",
   "metadata": {},
   "outputs": [],
   "source": [
    "sp.integrate(sp.exp(-x**2), x), sp.integrate(sp.sin(x)/x, x)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c077",
   "metadata": {},
   "source": [
    "The functions $e^{-x^2}$ and $\\frac{\\sin x}{x}$ have no **elementary** antiderivatives — this is Liouville’s theorem (1835), not a weakness of the program; algorithms such as the Risch algorithm can decide such questions. SymPy expresses the result in terms of the special functions $\\operatorname{erf} x = \\frac{2}{\\sqrt{\\pi}}\\int_0^x e^{-t^2}\\,dt$ and $\\operatorname{Si} x = \\int_0^x \\frac{\\sin t}{t}\\,dt$, which are defined precisely as such integrals.\n",
    "\n",
    "Things are different with the integral $\\int_0^1 x^x\\,dx$; let us check what `integrate` returns and what the type of the result is:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c078",
   "metadata": {},
   "outputs": [],
   "source": [
    "I = sp.integrate(x**x, (x, 0, 1))\n",
    "I, type(I).__name__"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c079",
   "metadata": {},
   "source": [
    "SymPy leaves the integral $\\int_0^1 x^x\\,dx$ unevaluated, but it returns an object of the special type `NonElementaryIntegral`: the part of the **Risch algorithm** implemented in SymPy has *proved* that the function $x^x$ has no elementary antiderivative. (Curiously, `sp.N` does not compute the numerical value of such an object — for numerical computations, use the ordinary integral `sp.Integral(x**x, (x, 0, 1))`.)\n",
    "\n",
    "**Exercise.** (a) Compute the derivative of the function $x^x$. (b) Compute $\\int_0^\\infty e^{-x^2}\\,dx$. (c) Compute numerically, to 30 digits, the integral $\\int_0^1 x^x\\,dx$ (`sp.N(sp.Integral(x**x, (x, 0, 1)), 30)`) and the sum $\\sum_{k=1}^{\\infty} (-1)^{k+1} k^{-k}$ (`sp.Sum(...)`, then `sp.N`). Compare. This is the so-called “sophomore’s dream” (J. Bernoulli, 1697). Is agreement to 30 digits a proof?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c080",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c081",
   "metadata": {},
   "source": [
    "### B7. From formula to plot: `lambdify` ★\n",
    "\n",
    "A SymPy expression is convenient for transformations but slow for computations at thousands of points.\n",
    "The function `lambdify` turns it into an ordinary Python function that works on NumPy arrays — a bridge\n",
    "between the symbolic and the numerical world:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c082",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "f = sp.sin(x) / x\n",
    "f_num = sp.lambdify(x, f, \"numpy\")      # wyrażenie SymPy → szybka funkcja NumPy\n",
    "xs = np.linspace(-20, 20, 2000)         # parzysta liczba punktów: omijamy x = 0\n",
    "plt.figure(figsize=(8, 3))\n",
    "plt.plot(xs, f_num(xs))\n",
    "plt.title(r\"$\\sin x / x$\"); plt.grid(alpha=0.3)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c083",
   "metadata": {},
   "source": [
    "**Exercise.** (a) On the interval $[-2\\pi, 2\\pi]$, plot the function $\\sin x$ together with its Taylor polynomials of degrees $1, 3, 5, 7, 9$ (`sp.series(sp.sin(x), x, 0, st + 1).removeO()`, where `st` is the degree); set the range of the $y$-axis to $[-2, 2]$. (b) What is the smallest degree for which the Taylor polynomial approximates $\\sin x$ on $[-\\pi, \\pi]$ with an error less than $10^{-6}$? Determine it numerically (`np.max(np.abs(...))`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c084",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c085",
   "metadata": {},
   "source": [
    "### B8. Is $e^{\\pi\\sqrt{163}}$ an integer? ★★\n",
    "\n",
    "Let us compare three computations of the same number: in `float` arithmetic and in SymPy with $15$ and $40$ significant\n",
    "digits:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c086",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "R = sp.exp(sp.pi * sp.sqrt(163))\n",
    "print(math.exp(math.pi * math.sqrt(163)))   # arytmetyka float\n",
    "print(sp.N(R, 15))\n",
    "print(sp.N(R, 40))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c087",
   "metadata": {},
   "source": [
    "The number $e^{\\pi\\sqrt{163}}$ (known as Ramanujan’s constant) is **transcendental** (this follows from the Gelfond–Schneider theorem), and yet it differs from an integer by less than $10^{-12}$. Note also that the result computed in `float` arithmetic differs from the true value by several hundred!\n",
    "\n",
    "**Exercise.** (a) Explain where such a large error in `float` arithmetic comes from (*hint:* what is the absolute error of the computed exponent $\\pi\\sqrt{163} \\approx 40$, and what does the exponential function do to it?). (b) Compute $e^{\\pi\\sqrt{d}}$ to $40$ significant digits for $d \\in \\{19, 43, 67, 163\\}$. How close to integers are these values? (The numbers $19$, $43$, $67$, and $163$ are so-called Heegner numbers, and the closeness of $e^{\\pi\\sqrt{d}}$ to integers reflects deep algebraic number theory.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c088",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c089",
   "metadata": {},
   "source": [
    "### B9. Expression swell ★★\n",
    "\n",
    "We measure the size of an expression by the number of nodes in its tree.\n",
    "\n",
    "**Exercise.** (a) Write a function `liczba_wezlow(e)` that counts the nodes (use `sp.preorder_traversal`). (b) Compare the number of nodes of the expression $(x+y)^n$ and of its expansion for $n = 1, \\dots, 20$ — draw a plot. (c) Compare the number of nodes of $x^n - 1$ and of `sp.factor(x**n - 1)` for $n \\in \\{2, 6, 12, 30, 60\\}$. **Analysis:** is there a single “simplest” form of an expression? What does “simplify” mean in practice?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c090",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c091",
   "metadata": {},
   "source": [
    "## Part C — optional challenges\n",
    "\n",
    "### C1. Cube roots and branches ★★★\n",
    "\n",
    "Cardano’s formulas yield the identity $\\sqrt[3]{2+\\sqrt5} + \\sqrt[3]{2-\\sqrt5} = 1$ (for **real** roots). Let us check it in SymPy by computing the difference between the two sides numerically:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c092",
   "metadata": {},
   "outputs": [],
   "source": [
    "w = sp.cbrt(2 + sp.sqrt(5)) + sp.cbrt(2 - sp.sqrt(5)) - 1\n",
    "sp.N(w)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c093",
   "metadata": {},
   "source": [
    "The result is not zero, because $2 - \\sqrt5 < 0$, and `sp.cbrt` of a negative number $a$ is the **principal value** of the cube root, i.e., the complex number $|a|^{1/3} e^{i\\pi/3}$, not the real root.\n",
    "\n",
    "**Exercise.** (a) Compare `sp.N(sp.cbrt(-8))` and `sp.real_root(-8, 3)`. (b) Repeat the computation for the real roots: compute `s_expr = sp.real_root(2 + sp.sqrt(5), 3) + sp.real_root(2 - sp.sqrt(5), 3)` and simplify `s_expr - 1`. (c) Prove the identity on paper: for $u = \\sqrt[3]{2+\\sqrt5}$, $v = \\sqrt[3]{2-\\sqrt5}$, and $s = u + v$ we have $u^3 + v^3 = 4$ and $uv = -1$, so $s^3 = 4 - 3s$. Factor $s^3 + 3s - 4$ and conclude that $s = 1$. (d) Compare with the output of `sp.minimal_polynomial(s_expr, x)`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c094",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c095",
   "metadata": {},
   "source": [
    "### C2. Quotient rings and Gröbner bases ★★★\n",
    "\n",
    "Exercise B4 has a “lightning-fast” solution in SageMath — a computation in the **quotient ring** $\\mathbb{Q}[a, b, m]/(ab - 1,\\ a + b + m)$:\n",
    "\n",
    "```python\n",
    "# SageMath (np. https://sagecell.sagemath.org) — ten kod NIE działa w czystym Pythonie\n",
    "R.<aa,bb,mm> = PolynomialRing(QQ, 3)\n",
    "I = R.ideal([aa*bb - 1, aa + bb + mm])          # relacje: αβ = 1, α + β = -m\n",
    "S.<abar,bbar,mbar> = R.quotient_ring(I)\n",
    "1/abar^3 + 1/bbar^3                              # wynik: wielomian zmiennej mbar\n",
    "```\n",
    "\n",
    "In SymPy, we carry out the same computation using a **Gröbner basis** of the ideal of relations and reducing the polynomial modulo this basis.\n",
    "\n",
    "**Exercise.** (a) Create the symbols `a, b, m = sp.symbols('a b m')` and compute `G = sp.groebner([a*b - 1, a + b + m], a, b, m, order='lex')`. (b) Since $ab = 1$, we have $\\frac{1}{a^3} + \\frac{1}{b^3} = a^3 + b^3$ — reduce this polynomial: `G.reduce(a**3 + b**3)` returns a pair (list of quotients, remainder), and the result of the reduction is the remainder. Compare with the result of B4. (c) Using the same method, express $\\alpha^5 + \\beta^5$ in terms of $m$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c096",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c097",
   "metadata": {},
   "source": [
    "### C3. Power sums — Faulhaber’s formula ★★★\n",
    "\n",
    "**Exercise.** (a) For $p = 0, 1, \\dots, 10$, compute $S_p(n) = \\sum_{k=1}^{n} k^p$ and factor the result. (b) Print the coefficients of the polynomial $S_p(n)$ (`sp.Poly(S, n).all_coeffs()`). What is the leading coefficient? And the next one? (c) Check that for odd $p \\ge 3$ the polynomial $S_p(n)$ is divisible by $n^2(n+1)^2$. (d) Compare the coefficient of $n$ with the Bernoulli number `sp.bernoulli(p)`. (This will be useful in exercise Z2 at the end of the set.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c098",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c099",
   "metadata": {},
   "source": [
    "## Part D — one example, three worlds (≈ 15 min or at home)\n",
    "\n",
    "In the lecture we compared three ways of “knowing” that\n",
    "\n",
    "$$1 + 2 + \\dots + n = \\frac{n(n+1)}{2}.$$\n",
    "\n",
    "Now you will go through them on your own: **numerically** (we check cases — and watch out for machine arithmetic), **symbolically** (a CAS transforms formulas according to algorithms we trust), and **formally** (a proof checked by the kernel of a proof assistant).\n",
    "\n",
    "### D1. The numerical world ★\n",
    "\n",
    "**Exercise.**\n",
    "\n",
    "(a) Using Python integers, check that `sum(range(1, n + 1)) == n*(n + 1)//2` for all $n \\le 2000$.\n",
    "\n",
    "(b) Now sum in **single-precision** arithmetic: start with `s = np.float32(0)` and add the successive numbers $1, 2, 3, \\dots$, rounding to the type `np.float32` after each addition, i.e., `s = np.float32(s + np.float32(i))`. What is the **smallest** $n$ for which the result first differs from $n(n+1)/2$? What is the “machine” sum then, and what is the true one?\n",
    "\n",
    "(c) **Analysis:** compare the sum obtained with the number $2^{24} = 16{,}777{,}216$. The `float32` type has a 24-bit significand — which integers can it store exactly? Why is the wrong value **even**?\n",
    "\n",
    "(d) Why is the same computation in `float64` arithmetic (an ordinary `float`) guaranteed to be exact as long as $n(n+1)/2 \\le 2^{53}$, i.e., for $n \\le 134{,}217{,}727$?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c100",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c101",
   "metadata": {},
   "source": [
    "### D2. The symbolic world ★\n",
    "\n",
    "In the symbolic world we do not check cases; instead, we ask the CAS for a formula:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c102",
   "metadata": {},
   "outputs": [],
   "source": [
    "k, n = sp.symbols('k n', integer=True, positive=True)\n",
    "S = sp.summation(k, (k, 1, n))\n",
    "S, sp.factor(S)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c103",
   "metadata": {},
   "source": [
    "SymPy returns $\\frac{n^2}{2} + \\frac{n}{2} = \\frac{n(n+1)}{2}$.\n",
    "\n",
    "**Exercise.**\n",
    "\n",
    "(a) In the same way, compute $\\sum_{k=1}^n k^2$ and $\\sum_{k=1}^n k^3$ and factor the results.\n",
    "\n",
    "(b) Check the **induction step** symbolically: for $T(n) = \\frac{n(n+1)}{2}$, compute `sp.simplify(T(n + 1) - T(n) - (n + 1))`.\n",
    "\n",
    "(c) **Analysis:** the result of (b) looks like a proof by induction. Why is it rather a **pseudo-proof**? Point out what we trust (the implementations of `summation` and `simplify`), what we have not checked (the base case, the induction principle itself, the correctness of the transformations), and what is missing (a certificate that someone could verify independently)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c104",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c105",
   "metadata": {},
   "source": [
    "### D3. The formal world: a proof in Peano Lab ★ – ★★★\n",
    "\n",
    "**Peano Lab** is a simple system for proving theorems of Peano arithmetic in its intuitionistic version (Heyting arithmetic), running in the browser: <https://bnaskrecki.faculty.wmi.amu.edu.pl/peano-lab/>. Its language contains only $0$, the successor $S$, addition, and multiplication — **there is no summation symbol $\\Sigma$ and no division**. That is why the honest version of Gauss’s formula in this language is the statement that $n(n+1)$ is even, i.e., that $\\frac{n(n+1)}{2} \\in \\mathbb{N}$:\n",
    "\n",
    "$$\\forall n\\ \\exists x\\ \\ n \\cdot (n+1) = 2 \\cdot x.$$\n",
    "\n",
    "Each proof step (tactic) builds a piece of a **certificate**, and the command `qed` passes the whole certificate to an independent **kernel**, which checks it using only the rules of logic and equality, the axioms PA1–PA6, and the induction schema (type `pa axioms` to see them).\n",
    "\n",
    "<a href=\"https://bnaskrecki.faculty.wmi.amu.edu.pl/peano-lab/?cmd=pa%20prove%20forall%20n.%20exists%20x.%20n%20*%20(n%20%2B%201)%20%3D%202%20*%20x\" target=\"_blank\">Open Peano Lab with this theorem</a> and enter the commands one at a time (or paste the whole script using the *paste multiline proof* button):\n",
    "\n",
    "```text\n",
    "pa prove forall n. exists x. n * (n + 1) = 2 * x\n",
    "induction n\n",
    "exists 0\n",
    "ring\n",
    "cases IH\n",
    "exists x + S n\n",
    "trans n * (n + 1) + 2 * S n\n",
    "ring\n",
    "rewrite IH_witness\n",
    "ring\n",
    "qed\n",
    "```\n",
    "\n",
    "**What happens at each step?**\n",
    "\n",
    "- `induction n` — proof by induction: two goals arise, the **base case** ($n = 0$) and the **induction step** (with the induction hypothesis `IH`).\n",
    "- `exists 0`, `ring` — in the base case the witness is $x = 0$, since $0 \\cdot (0 + 1) = 2 \\cdot 0$; the polynomial identity is closed by the `ring` tactic.\n",
    "- `cases IH` — we unpack the induction hypothesis: we get a witness $x$ and the equation `IH_witness`: $n(n+1) = 2x$.\n",
    "- `exists x + S n` — the witness for $S\\,n = n + 1$ is $x + (n + 1)$, since $(n+1)(n+2) = n(n+1) + 2(n+1)$.\n",
    "- `trans n * (n + 1) + 2 * S n` — via the intermediate expression, we split the goal $S\\,n \\cdot (S\\,n + 1) = 2 \\cdot (x + S\\,n)$ into two equations; the first one, $S\\,n \\cdot (S\\,n + 1) = n(n+1) + 2 \\cdot S\\,n$, is closed by `ring`.\n",
    "- `rewrite IH_witness`, `ring` — in the second equation we replace $n(n+1)$ with $2x$ and close the identity $2x + 2 \\cdot S\\,n = 2 \\cdot (x + S\\,n)$.\n",
    "- `qed` — the independent kernel checks the whole certificate against the original theorem, and Peano Lab responds with the message `No open goals. QED`. The command `script` then prints the report `Independent kernel check: PASS (22847 certificate nodes)`: the kernel check has passed, and the certificate has $22{,}847$ nodes.\n",
    "\n",
    "The proof is **constructive**: the witness satisfies $x_0 = 0$ and $x_{n+1} = x_n + (n + 1)$, so $x_n = 0 + 1 + \\dots + n$ — the proof “contains” an algorithm for computing the sum!\n",
    "\n",
    "**Exercises** (you do them in the browser, in Peano Lab — not in this notebook):\n",
    "\n",
    "1. ★ Warm-up: prove `forall n. 0 + n = n` (script: `pa prove forall n. 0 + n = n`, `induction n`, `ring`, `ring`, `qed`) and `forall n. exists x. n + n = 2 * x` (`pa prove forall n. exists x. n + n = 2 * x`, `intro n`, `exists n`, `ring`, `qed`). Why does the first theorem require induction, even though $n + 0 = n$ is axiom PA3?\n",
    "2. ★ Reproduce the proof of Gauss’s formula given above. After `qed`, type `script` and read off the size of the certificate.\n",
    "3. ★★ Adapt the proof to the sum of squares: `forall n. exists x. n * (n + 1) * (2 * n + 1) = 6 * x`. *Hint:* what is the witness for $n + 1$, given that $\\sum_{k=1}^{n+1} k^2 = \\sum_{k=1}^{n} k^2 + (n+1)^2$? What intermediate expression should you give to `trans`?\n",
    "4. ★★★ Prove the theorem for the sum of cubes in the same way: `forall n. exists x. n * n * (n + 1) * (n + 1) = 4 * x`.\n",
    "5. What happens if you give a **wrong** witness, e.g., `exists x + n` in the proof of Gauss’s formula? Try it and describe the message.\n",
    "6. In the Markdown cell below, explain in your own words how the witness $x$ in the proofs from exercises 2–4 is related to the sums $\\sum k$, $\\sum k^2$, $\\sum k^3$, and compare the three worlds (D1–D3): what each of them guarantees and what it does not."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c106",
   "metadata": {},
   "source": [
    "*Your answer (exercise D3.6):* …"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c107",
   "metadata": {},
   "source": [
    "## Exercises for independent practice\n",
    "\n",
    "The rules are the same as in Lab 1: the exercises are for your own practice, and each of them is **a single function** with the given name that **returns** its result. You may use SymPy (`import sympy as sp`) or plain Python (the modules `fractions` and `math`) — only the returned value matters.\n",
    "\n",
    "### Z1. Powers of the golden ratio ★\n",
    "\n",
    "Let $m$ satisfy the equation $m^2 + m - 1 = 0$ (i.e., $m = \\frac{1}{1+m}$). For every $n \\ge 0$ there exist uniquely determined integers $a_n, b_n$ such that $m^n = a_n + b_n m$ (for **both** roots $m$ simultaneously). Write a function `potega_m(n)` that returns the tuple `(a_n, b_n)` of integers.\n",
    "\n",
    "Examples: `potega_m(0) == (1, 0)`, `potega_m(2) == (1, -1)`, `potega_m(10) == (34, -55)`.\n",
    "\n",
    "*Hint:* the remainder of $x^n$ upon division by $x^2 + x - 1$ (exercise B5), or the recurrence that follows from $m^{n+1} = m \\cdot m^n$.\n",
    "\n",
    "### Z2. Power sums ★★\n",
    "\n",
    "Write a function `wspolczynniki_sumy_poteg(p)` that, for $p \\ge 0$, returns the list of coefficients of the polynomial $S_p(n) = \\sum_{k=1}^{n} k^p$ (in the variable $n$), from the coefficient of $n^{p+1}$ down to the constant term — the list has length $p + 2$. The coefficients must be **exact** rational numbers: `fractions.Fraction` or `sympy.Rational` (the test prints `str()` of each element of the list). The function must work for $p \\le 30$.\n",
    "\n",
    "Examples: for $p = 1$ we have $S_1(n) = \\frac12 n^2 + \\frac12 n$, so `[str(c) for c in wspolczynniki_sumy_poteg(1)] == ['1/2', '1/2', '0']`; for $p = 2$ the result is `['1/3', '1/2', '1/6', '0']`.\n",
    "\n",
    "### Z3. The last digit of $A_n$ ★★★\n",
    "\n",
    "For $(1 + \\sqrt2)^n = A_n + B_n\\sqrt2$ ($A_n, B_n \\in \\mathbb{Z}$), write a function `ostatnia_cyfra_A(n)` that returns the last decimal digit of $A_n$ for $0 \\le n \\le 10^{18}$.\n",
    "\n",
    "Examples: `ostatnia_cyfra_A(3) == 7` (since $(1+\\sqrt2)^3 = 7 + 5\\sqrt2$), `ostatnia_cyfra_A(1000) == 7`.\n",
    "\n",
    "*Hint:* for $n = 10^{18}$, neither expanding the power nor a loop of $n$ steps will finish in time. Study the sequence $A_n \\bmod 10$ (exercise B2(d)) — and justify your observation — or use fast exponentiation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c108",
   "metadata": {},
   "outputs": [],
   "source": [
    "def potega_m(n):\n",
    "    # TWÓJ KOD\n",
    "    ...\n",
    "\n",
    "def wspolczynniki_sumy_poteg(p):\n",
    "    # TWÓJ KOD\n",
    "    ...\n",
    "\n",
    "def ostatnia_cyfra_A(n):\n",
    "    # TWÓJ KOD\n",
    "    ...\n",
    "\n",
    "# Testy lokalne — odkomentuj, gdy funkcje będą gotowe:\n",
    "# assert potega_m(0) == (1, 0) and potega_m(2) == (1, -1) and potega_m(10) == (34, -55)\n",
    "# assert [str(c) for c in wspolczynniki_sumy_poteg(2)] == ['1/3', '1/2', '1/6', '0']\n",
    "# assert ostatnia_cyfra_A(3) == 7 and ostatnia_cyfra_A(1000) == 7\n",
    "# print(\"Testy przykładowe przechodzą.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c109",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "**Next:** the theme of machine arithmetic from exercise D1 is developed further in the deep dive {doc}`../ieee754/ieee754` and in the problem set {doc}`lab03_ieee754`."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
