{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c000",
   "metadata": {},
   "source": [
    "# Lab 1: VS Code, Jupyter, and Python as a mathematician’s calculator\n",
    "\n",
    "**Duration:** 90 min · **Lecture:** {doc}`Lecture 1 — working environment <../wyklady/w01_1_srodowisko>`\n",
    "\n",
    "## Learning goals\n",
    "\n",
    "After this session you will be able to:\n",
    "\n",
    "1. run a Jupyter notebook in **Visual Studio Code** with your own Python environment;\n",
    "2. write **Markdown** cells with $\\LaTeX$ formulas, as well as **code** cells;\n",
    "3. use Python’s arithmetic deliberately: integers of **arbitrary length** (`int`), **floating-point** numbers (`float`), and **exact fractions** (`Fraction`), as well as the operators `/`, `//`, `%`, `**`;\n",
    "4. express simple mathematical algorithms with loops, conditionals, functions, and list comprehensions.\n",
    "\n",
    "We work in the spirit of *computational thinking*: **abstraction** (we formulate the problem precisely) → **automation** (we write the solution as a program) → **analysis** (we check and interpret the result — especially when the computer shows something surprising).\n",
    "\n",
    "```{admonition} How to work with this problem set\n",
    ":class: tip\n",
    "Download the notebook (the download button at the top of the page → `.ipynb`), open it in VS Code, and fill in the cells marked `# TWÓJ KOD` (“your code”). Legend: ★ — basic exercise, ★★ — intermediate, ★★★ — optional challenge. The set ends with **exercises for independent practice**.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c001",
   "metadata": {},
   "source": [
    "## 0. Setting up the environment (≈ 15 min)\n",
    "\n",
    "1. **Visual Studio Code** — download it from <https://code.visualstudio.com>. In the *Extensions* panel (`Ctrl+Shift+X`, on macOS `Cmd+Shift+X`), install the **Python** and **Jupyter** extensions (publisher: Microsoft).\n",
    "2. **Python 3.12 or newer** — <https://www.python.org/downloads/> (in the Windows installer, check *Add python.exe to PATH*); on macOS you can also use `brew install python`, and on Linux your package manager. Check in a terminal: `python3 --version` (Windows: `py --version`).\n",
    "3. **Course folder and virtual environment.** Create a folder, e.g., `krpm`, open it in VS Code (*File → Open Folder…*), open a terminal (*Terminal → New Terminal*), and type:\n",
    "   ```bash\n",
    "   python3 -m venv .venv                 # Windows: py -m venv .venv\n",
    "   source .venv/bin/activate             # Windows: .venv\\Scripts\\activate\n",
    "   python -m pip install sympy numpy matplotlib ipykernel\n",
    "   ```\n",
    "4. **Notebook.** Open the downloaded file `lab01_srodowisko_python.ipynb` (or create a new one: *File → New File… → Jupyter Notebook*), then click **Select Kernel** in the top right corner → *Python Environments* → `.venv`.\n",
    "5. Run the cell below with `Shift+Enter`. It prints the versions of Python and of the packages, and if a package is missing, it shows the command to install it.\n",
    "\n",
    "Detailed installation instructions (Windows, macOS, Linux): {doc}`../wyklady/w01_1_srodowisko`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c002",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys, platform\n",
    "print(\"Python:\", sys.version.split()[0], \"|\", platform.system())\n",
    "try:\n",
    "    import sympy, numpy, matplotlib\n",
    "    print(\"SymPy:\", sympy.__version__, \"| NumPy:\", numpy.__version__,\n",
    "          \"| Matplotlib:\", matplotlib.__version__)\n",
    "except ImportError as e:\n",
    "    print(\"Brakuje pakietu:\", e.name, \"— zainstaluj go poleceniem: python -m pip install\", e.name)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c003",
   "metadata": {},
   "source": [
    "```{admonition} If the installation fails\n",
    ":class: warning\n",
    "Do not spend the session fighting the installation — work in the browser for now and finish installing at home:\n",
    "- the faculty’s JupyterHub server (for WMI UAM students): <https://jupyter.wmi.amu.edu.pl>,\n",
    "- CoCalc: <https://cocalc.com> (Python and SageMath in the browser),\n",
    "- SageMathCell: <https://sagecell.sagemath.org> (quick one-off computations).\n",
    "```\n",
    "\n",
    "**Key notebook shortcuts (VS Code):**\n",
    "\n",
    "| Shortcut | Action |\n",
    "|---|---|\n",
    "| `Shift+Enter` | run the cell and move to the next one |\n",
    "| `Ctrl+Enter` | run the cell and stay in it |\n",
    "| `Esc`, then `A` / `B` | new cell above / below |\n",
    "| `Esc`, then `M` / `Y` | change the cell type to Markdown / code |\n",
    "| `Esc`, then `D`, `D` | delete the cell |\n",
    "| `Ctrl+Shift+P` (macOS: `Cmd+Shift+P`) | VS Code command palette |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c004",
   "metadata": {},
   "source": [
    "## Part A — warm-up (≈ 20 min)\n",
    "\n",
    "### A1. A Markdown cell with a formula ★\n",
    "\n",
    "Markdown cells are for writing comments, and formulas are written in $\\LaTeX$ syntax: `$...$` inside text, `$$...$$` on a separate line. Double-click the cell below to see its source."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c005",
   "metadata": {},
   "source": [
    "**Binet’s formula.** For $n \\ge 0$, the Fibonacci numbers ($F_0 = 0$, $F_1 = 1$, $F_{n+2} = F_{n+1} + F_n$) satisfy\n",
    "\n",
    "$$F_n = \\frac{1}{\\sqrt{5}}\\left(\\left(\\frac{1+\\sqrt{5}}{2}\\right)^{n} - \\left(\\frac{1-\\sqrt{5}}{2}\\right)^{n}\\right).$$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c006",
   "metadata": {},
   "source": [
    "**Exercise.** Insert a new Markdown cell below (`Esc`, `B`, `M`) and write in it:\n",
    "\n",
    "1. the formula for the roots of the quadratic equation $ax^2 + bx + c = 0$ (with the discriminant $\\Delta$),\n",
    "2. the formula for the sum of a geometric series $\\sum_{k=0}^{n} q^k = \\dfrac{1-q^{n+1}}{1-q}$ for $q \\neq 1$,\n",
    "3. the set $\\{\\, d \\in \\mathbb{N} : d \\mid 12 \\,\\}$ — list its elements."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c007",
   "metadata": {},
   "source": [
    "### A2. Integers have no length limit ★\n",
    "\n",
    "In Python, numbers of type `int` can be arbitrarily long — the only limit is the computer’s memory.\n",
    "Let us compute $2^{1000}$ and count the decimal digits of this number:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c008",
   "metadata": {},
   "outputs": [],
   "source": [
    "n = 2**1000\n",
    "print(n)\n",
    "print(\"liczba cyfr:\", len(str(n)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c009",
   "metadata": {},
   "source": [
    "**Exercise.** Compute the sum of the digits of $2^{1000}$. *Hint:* `str(n)` converts a number to a string, and `int(c)` converts a one-character string `c`, e.g., `'7'`, to the number $7$. (Check: the sum is $1366$.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c010",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c011",
   "metadata": {},
   "source": [
    "The `float` type has a limited range and precision (about 16 significant digits):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c012",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(2.0**1000)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c013",
   "metadata": {},
   "source": [
    "Python printed the shortest decimal representation that uniquely determines this `float` number (here,\n",
    "17 significant digits). The number $2^{1000}$ itself, being a power of two, is stored exactly in the\n",
    "`float` type, but neighboring `float` numbers in the interval $[2^{1000}, 2^{1001})$ are $2^{948}$\n",
    "apart, so, for example, the number $2^{1000} + 1$ can no longer be represented. The range is limited as\n",
    "well: the largest finite `float` number is $(2-2^{-52})\\cdot2^{1023}\\approx1.8\\cdot10^{308}$,\n",
    "so $2^{1024}$ lies outside it. Converting an integer that is too large into a `float` raises an\n",
    "error:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c014",
   "metadata": {
    "tags": [
     "raises-exception"
    ]
   },
   "outputs": [],
   "source": [
    "float(2**1024)   # liczba zbyt duża dla typu float → OverflowError"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c015",
   "metadata": {},
   "source": [
    "The cell above fails on purpose. Read the error message — it is information, too!\n",
    "\n",
    "### A3. Division: `/`, `//`, `%` ★\n",
    "\n",
    "Python has three operators related to division: for integers, `/` always gives a result of type\n",
    "`float`, `//` gives the integer quotient, and `%` the remainder. The function `divmod` returns the quotient and the remainder at once.\n",
    "Let us try them on positive and negative numbers:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c016",
   "metadata": {},
   "outputs": [],
   "source": [
    "a, b = 17, 5\n",
    "print(a / b, a // b, a % b, divmod(a, b))\n",
    "print(-7 // 2, -7 % 2)      # uwaga na liczby ujemne!"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c017",
   "metadata": {},
   "source": [
    "For integers $a$ and $b \\ne 0$, the expression `a // b` is the **floor** of the quotient, $\\lfloor a/b \\rfloor$, and `a % b` is the remainder $a \\bmod b = a - b\\lfloor a/b \\rfloor$, which is either zero or has the sign of the divisor. Hence we always have\n",
    "\n",
    "$$a = b \\cdot \\left\\lfloor \\frac{a}{b} \\right\\rfloor + (a \\bmod b), \\qquad 0 \\le a \\bmod b < b \\quad \\text{for } b > 0.$$\n",
    "\n",
    "In C, C++, and Java, integer division **truncates** the result toward zero: there `-7/2 == -3` and `-7%2 == -1` (in Python, these values are given by `int(-7/2)` and `math.fmod(-7, 2)`, respectively). When you port an algorithm between languages, it is easy to introduce a subtle bug!\n",
    "\n",
    "**Exercise.** Verify by computer that `a == b*(a//b) + a % b` holds for all $a \\in \\{-20, \\dots, 20\\}$ and $b \\in \\{-20, \\dots, 20\\} \\setminus \\{0\\}$. Use the function `all(...)` — the computer counterpart of the quantifier $\\forall$ (the counterpart of $\\exists$ is `any(...)`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c018",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD: zamień ... na wyrażenie z all(...)\n",
    "wynik = ...\n",
    "print(wynik)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c019",
   "metadata": {},
   "source": [
    "**Analysis.** Is such a check a proof of this identity for *all* integers? What would it take to prove it?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c020",
   "metadata": {},
   "source": [
    "### A4. A pitfall: `^` is not exponentiation ★\n",
    "\n",
    "In plain text (e.g., in an email) and in many programs, including SageMath, the power $x^{10}$ is\n",
    "written as `x^10`. In Python, this notation means something entirely different:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c021",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(2 ** 10, 2 ^ 10)          # potęga vs. XOR (alternatywa wykluczająca na bitach)\n",
    "print(bin(2), bin(10), bin(2 ^ 10))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c022",
   "metadata": {},
   "source": [
    "The `^` operator computes the bitwise exclusive or (XOR): a bit of the result is $1$ exactly where the bits of the operands differ, e.g., $0010_2 \\oplus 1010_2 = 1000_2 = 8$. In **SageMath**, `^` means exponentiation (Sage preprocesses the code before passing it on to Python) — when switching between SymPy and Sage, it is easy to make a mistake.\n",
    "\n",
    "### A5. Floating-point numbers: surprises ★\n",
    "\n",
    "Numbers of type `float` are represented in binary, so most decimal fractions can be stored only\n",
    "approximately. Let us see what this implies even for the computation $0.1 + 0.2$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c023",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(0.1 + 0.2 == 0.3)\n",
    "print(0.1 + 0.2)\n",
    "print(f\"{0.1:.25f}\")\n",
    "print((0.1).as_integer_ratio())     # dokładna wartość przechowywana w pamięci"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c024",
   "metadata": {},
   "source": [
    "The number $0.1$ has no finite binary expansion, so the computer stores the nearest machine number, i.e., a number of the form $m \\cdot 2^{e}$ with integers $m$ and $e$, where $0 \\le m < 2^{53}$; here $0.1 \\approx 3602879701896397/2^{55}$. You can see the bits of this number in the <a href=\"../../applets/float-explorer.html\" target=\"_blank\">“Anatomy of a floating-point number” applet</a>.\n",
    "\n",
    "When exact computation is needed, we use fractions (`Fraction`); when an approximate result is enough, we compare `float` numbers with a tolerance (`math.isclose`):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c025",
   "metadata": {},
   "outputs": [],
   "source": [
    "from fractions import Fraction\n",
    "import math\n",
    "\n",
    "print(Fraction(1, 10) + Fraction(2, 10) == Fraction(3, 10))   # ułamki dokładne\n",
    "print(Fraction(0.1))                    # ułamek równy (dokładnie!) liczbie float 0.1\n",
    "print(math.isclose(0.1 + 0.2, 0.3))     # porównanie z tolerancją"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c026",
   "metadata": {},
   "source": [
    "**Exercise.** Compute $\\sum_{k=1}^{10} \\frac{1}{10}$ in three ways: (a) with a loop `s = 0.0; for ...: s += 0.1` on `float` numbers, (b) with the function `math.fsum`, (c) with exact fractions (`Fraction`). Compare the results with the number $1$. Which results are equal to $1$? Which method computes exactly, and which one returns only the correctly rounded sum of the stored `float` numbers? *Hint:* the exact sum of ten `float` numbers equal to `0.1` is given by `sum([Fraction(0.1)] * 10)`.\n",
    "\n",
    "(d) Also compute `sum([0.1] * 10)`. In Python 3.12 and newer, the result differs from the loop in (a) — look up the documentation of the `sum` function and explain what has changed. (In older versions of Python, the result is the same as with the loop.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c027",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c028",
   "metadata": {},
   "source": [
    "## Part B — main exercises (≈ 45 min)\n",
    "\n",
    "### B1. Sets as list comprehensions ★\n",
    "\n",
    "Set-builder notation has a close relative in Python — the **list comprehension**:\n",
    "\n",
    "| Mathematics | Python |\n",
    "|---|---|\n",
    "| $\\{\\, n^2 : n \\in \\mathbb{N},\\ 1 \\le n \\le 10 \\,\\}$ | `[n**2 for n in range(1, 11)]` |\n",
    "| $\\{\\, p \\le 100 : p \\text{ is prime} \\,\\}$ | `[p for p in range(2, 101) if czy_pierwsza(p)]` |\n",
    "| $\\forall_{x \\in A}\\ \\varphi(x)$ | `all(phi(x) for x in A)` |\n",
    "| $\\exists_{x \\in A}\\ \\varphi(x)$ | `any(phi(x) for x in A)` |\n",
    "\n",
    "We define the function `czy_pierwsza` from the table by trial division: a number $n \\ge 2$ is prime\n",
    "if it is not divisible by any number $d$ with $2 \\le d \\le \\lfloor\\sqrt{n}\\rfloor$ (if $n = de$\n",
    "and $2 \\le d \\le e$, then $d \\le \\sqrt{n}$). Let us list the primes less than $100$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c029",
   "metadata": {},
   "outputs": [],
   "source": [
    "from math import isqrt\n",
    "\n",
    "def czy_pierwsza(n):\n",
    "    \"\"\"Czy n jest liczbą pierwszą? (dzielenie próbne do pierwiastka z n)\"\"\"\n",
    "    if n < 2:\n",
    "        return False\n",
    "    return all(n % d != 0 for d in range(2, isqrt(n) + 1))\n",
    "\n",
    "pierwsze = [p for p in range(2, 101) if czy_pierwsza(p)]\n",
    "print(pierwsze)\n",
    "print(len(pierwsze), \"liczb pierwszych mniejszych od 100\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c030",
   "metadata": {},
   "source": [
    "**Exercise.**\n",
    "\n",
    "(a) Print the set $P_1 = \\{\\, p < 200 : p \\text{ prime},\\ p \\equiv 1 \\pmod 4 \\,\\}$.\n",
    "\n",
    "(b) Check that **every** number in $P_1$ is a sum of two squares of natural numbers, and that **no** prime $p < 200$ with $p \\equiv 3 \\pmod 4$ is (these are instances of Fermat’s theorem on sums of two squares).\n",
    "\n",
    "(c) For each $p \\in P_1$, print the representation $p = a^2 + b^2$ with $a \\le b$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c031",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c032",
   "metadata": {},
   "source": [
    "### B2. Digits in an arbitrary base ★\n",
    "\n",
    "The representation of a number $n$ in base $b \\ge 2$ is $n = \\sum_{i=0}^{k} c_i b^i$, where $0 \\le c_i < b$ and, for $n > 0$, also $c_k \\ne 0$. We obtain the digits by repeated division with remainder by $b$.\n",
    "\n",
    "**Exercise.**\n",
    "\n",
    "(a) Write a function `cyfry(n, b=10)` that returns the list of digits of a number $n \\ge 0$ in base $b$, starting with the most significant one (for $n = 0$ it returns `[0]`). Compare `cyfry(2026, 2)` with the output of `bin(2026)`.\n",
    "\n",
    "(b) Write a function `suma_cyfr(n, b=10)` that returns the sum of the digits of a number $n \\ge 0$ in base $b$.\n",
    "\n",
    "(c) For which $n \\in \\{0, 1, \\dots, 100\\}$ is the sum of the decimal digits of $2^n$ divisible by $9$? **Analysis:** explain the result. *Hint:* a number and its digit sum leave the same remainder upon division by $9$ — why?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c033",
   "metadata": {},
   "outputs": [],
   "source": [
    "def cyfry(n, b=10):\n",
    "    \"\"\"Lista cyfr liczby n >= 0 w bazie b, od najbardziej znaczącej.\"\"\"\n",
    "    # TWÓJ KOD\n",
    "    ...\n",
    "\n",
    "def suma_cyfr(n, b=10):\n",
    "    # TWÓJ KOD\n",
    "    ...\n",
    "\n",
    "# Testy (odkomentuj, gdy funkcje będą gotowe):\n",
    "# print(cyfry(2026, 2), bin(2026))\n",
    "# print(cyfry(0), cyfry(255, 16), suma_cyfr(2**1000))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c034",
   "metadata": {},
   "source": [
    "### B3. The Collatz sequence ★\n",
    "\n",
    "For $n \\ge 1$, we define $c_0 = n$ and\n",
    "\n",
    "$$c_{k+1} = \\begin{cases} c_k / 2, & c_k \\text{ even},\\\\ 3c_k + 1, & c_k \\text{ odd}. \\end{cases}$$\n",
    "\n",
    "The **Collatz conjecture** (an open problem!) states that for every $n$ the sequence eventually reaches $1$. It has been verified by computer for all $n < 2^{71}$ (D. Bařina, 2025) — but that is not a proof.\n",
    "\n",
    "**Exercise.**\n",
    "\n",
    "(a) Write a function `collatz(n)` that returns the list $[c_0, c_1, \\dots, 1]$; check that `collatz(6) == [6, 3, 10, 5, 16, 8, 4, 2, 1]`.\n",
    "\n",
    "(b) Write a function `collatz_dlugosc(n)` that returns the number of steps needed to reach $1$ (for $n = 1$ it is $0$; `collatz_dlugosc(27) == 111`).\n",
    "\n",
    "(c) Find the $n < 10{,}000$ with the longest trajectory (you should get $261$ steps).\n",
    "\n",
    "(d) Draw a scatter plot of $n \\mapsto$ `collatz_dlugosc(n)` for $n < 10{,}000$ (`plt.scatter(..., s=1)`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c035",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "def collatz(n):\n",
    "    # TWÓJ KOD\n",
    "    ...\n",
    "\n",
    "def collatz_dlugosc(n):\n",
    "    # TWÓJ KOD\n",
    "    ...\n",
    "\n",
    "# print(collatz(6), collatz_dlugosc(27))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c036",
   "metadata": {},
   "source": [
    "### B4. The Euclidean algorithm and Fibonacci numbers ★★\n",
    "\n",
    "For integers $a, b \\ge 0$ we have $\\gcd(a, 0) = a$ and, if $b \\ge 1$, also $\\gcd(a, b) = \\gcd(b,\\ a \\bmod b)$. Since $0 \\le a \\bmod b < b$, the second argument decreases at every step, so the loop below terminates. Hence the **Euclidean algorithm**:\n",
    "\n",
    "```python\n",
    "while b != 0:\n",
    "    a, b = b, a % b\n",
    "```\n",
    "\n",
    "**Exercise.**\n",
    "\n",
    "(a) Write a function `nwd_kroki(a, b)` that returns the pair `(d, k)`: $d = \\gcd(a, b)$ and the number $k$ of divisions with remainder performed (loop iterations). Compare $d$ with `math.gcd` for a few hundred random pairs (`random.randint`).\n",
    "\n",
    "(b) For $k = 1, 2, \\dots, 10$, find the smallest pair $a > b \\ge 1$ (smallest $a$ first, then smallest $b$) for which the algorithm performs **exactly** $k$ steps. Search among $a < 200$.\n",
    "\n",
    "(c) What numbers do you see? Formulate a conjecture.\n",
    "\n",
    "(d) How fast do these numbers grow? Compute the ratios of consecutive values of $a$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c037",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math, random\n",
    "\n",
    "def nwd_kroki(a, b):\n",
    "    # TWÓJ KOD\n",
    "    ...\n",
    "\n",
    "# print(nwd_kroki(1071, 462))   # oczekiwane: (21, 3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c038",
   "metadata": {},
   "source": [
    "```{admonition} Lamé’s theorem (1844)\n",
    ":class: important dropdown\n",
    "Let $a > b \\ge 1$ be integers. If the Euclidean algorithm performs exactly $k$ divisions with remainder for them, then $a \\ge F_{k+2}$ and $b \\ge F_{k+1}$, and the pair $(F_{k+2}, F_{k+1})$ requires exactly $k$ divisions. Consequently, the number of steps never exceeds five times the number of decimal digits of the smaller number. This is one of the earliest results in history on the computational complexity of an algorithm.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c039",
   "metadata": {},
   "source": [
    "### B5. Square roots by Heron’s method ★★\n",
    "\n",
    "To approximate $\\sqrt{a}$ for $a > 0$, we start from $x_0 > 0$ and iterate\n",
    "\n",
    "$$x_{k+1} = \\frac{1}{2}\\left(x_k + \\frac{a}{x_k}\\right).$$\n",
    "\n",
    "This is a special case of **Newton’s method** for $f(x) = x^2 - a$ — we will return to it later in the course.\n",
    "\n",
    "**Exercise.**\n",
    "\n",
    "(a) For $a = 2$, $x_0 = 1$, perform 6 iterations with `float` numbers; print $x_k$ and the error $|x_k - \\sqrt{2}|$ (use `math.sqrt(2)`). What happens to the number of correct digits?\n",
    "\n",
    "(b) Repeat the computation with exact fractions (`Fraction`, 4 iterations). For the approximations $p/q$ obtained, compute $p^2 - 2q^2$. What do you notice?\n",
    "\n",
    "(c) **Analysis:** why does the error in (a) stop decreasing at roughly the $10^{-16}$ level?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c040",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c041",
   "metadata": {},
   "source": [
    "### B6. Divisors and perfect numbers ★\n",
    "\n",
    "The proper divisors of a natural number $n \\ge 1$ are its positive divisors less than $n$. A number $n$ is **perfect** if it equals the sum of its proper divisors, e.g., $6 = 1 + 2 + 3$.\n",
    "\n",
    "**Exercise.**\n",
    "\n",
    "(a) Write a function `dzielniki(n)` that returns the sorted list of all positive divisors of $n$. It suffices to check $d \\le \\sqrt{n}$ — why?\n",
    "\n",
    "(b) Find all perfect numbers $n \\le 10{,}000$.\n",
    "\n",
    "(c) Check Euclid’s theorem: if $2^p - 1$ is prime, then $2^{p-1}(2^p - 1)$ is perfect (examine $p = 2, 3, 5, 7, 13$).\n",
    "\n",
    "(d) The numbers $220$ and $284$ are **amicable**: the sum of the proper divisors of each of them equals the other. Check this.\n",
    "\n",
    "*Fun fact:* it is still unknown whether an odd perfect number exists."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c042",
   "metadata": {},
   "outputs": [],
   "source": [
    "def dzielniki(n):\n",
    "    # TWÓJ KOD\n",
    "    ...\n",
    "\n",
    "# print(dzielniki(28))   # oczekiwane: [1, 2, 4, 7, 14, 28]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c043",
   "metadata": {},
   "source": [
    "### B7. Pythagorean triples ★\n",
    "\n",
    "**Exercise.**\n",
    "\n",
    "(a) List all triples $(a, b, c)$ of natural numbers with $a < b < c \\le 50$ and $a^2 + b^2 = c^2$. How many are there?\n",
    "\n",
    "(b) Select the **primitive** triples, i.e., those with $\\gcd(a, b) = 1$.\n",
    "\n",
    "(c) Primitive triples are produced by **Euclid’s formula**: legs $m^2 - n^2$ and $2mn$, hypotenuse $m^2 + n^2$, where $m > n \\ge 1$, $\\gcd(m, n) = 1$, and $m - n$ is odd. Use this formula to generate all primitive triples with $c \\le 50$, arrange the legs of each triple in increasing order (the formula may give them in either order; e.g., for $m = 4$, $n = 1$ you get $(15, 8, 17)$), and check that you get the same set as in (b)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c044",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c045",
   "metadata": {},
   "source": [
    "### B8. The sieve of Eratosthenes and timing ★★\n",
    "\n",
    "The **sieve of Eratosthenes** finds all primes $\\le n$: we write down the numbers $2, \\dots, n$ and, for successive primes $p \\le \\sqrt{n}$, cross out the multiples $p^2, p^2 + p, p^2 + 2p, \\dots$ not exceeding $n$. The numbers that remain are prime.\n",
    "\n",
    "**Exercise.**\n",
    "\n",
    "(a) Write a function `sito(n)` that returns the list of primes $\\le n$ (use a list of Boolean values `[True] * (n + 1)`).\n",
    "\n",
    "(b) Check: $\\pi(10^4) = 1229$, $\\pi(10^5) = 9592$, $\\pi(10^6) = 78{,}498$, where $\\pi(x)$ denotes the number of primes $\\le x$.\n",
    "\n",
    "(c) Compare the running time of `sito(10**5)` with the time it takes to compute the list `[p for p in range(2, 10**5 + 1) if czy_pierwsza(p)]` (use `time.perf_counter()`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c046",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "def sito(n):\n",
    "    # TWÓJ KOD\n",
    "    ..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c047",
   "metadata": {},
   "source": [
    "### B9. How many primes are there? A first plot ★\n",
    "\n",
    "The **prime number theorem** (J. Hadamard, Ch. de la Vallée Poussin, 1896) states that $\\pi(x) \\sim \\dfrac{x}{\\ln x}$, i.e., $\\dfrac{\\pi(x)}{x / \\ln x} \\to 1$ as $x \\to \\infty$. The code below draws both graphs (it uses its own short sieve written in NumPy, so it works independently of exercise B8)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c048",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "N = 100_000\n",
    "sito_np = np.ones(N + 1, dtype=bool)\n",
    "sito_np[:2] = False\n",
    "for p in range(2, int(N**0.5) + 1):\n",
    "    if sito_np[p]:\n",
    "        sito_np[p*p::p] = False\n",
    "pi_x = np.cumsum(sito_np)           # pi_x[x] = liczba liczb pierwszych <= x\n",
    "xs = np.arange(2, N + 1)\n",
    "\n",
    "plt.figure(figsize=(8, 4))\n",
    "plt.plot(xs, pi_x[2:], label=r\"$\\pi(x)$\")\n",
    "plt.plot(xs, xs / np.log(xs), label=r\"$x/\\ln x$\")\n",
    "plt.xlabel(\"$x$\"); plt.legend(); plt.title(\"Liczby pierwsze do $10^5$\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c049",
   "metadata": {},
   "source": [
    "Both curves grow similarly, and from $x = 17$ on, the curve $x/\\ln x$ stays below $\\pi(x)$\n",
    "(J. B. Rosser, L. Schoenfeld, 1962): at $x = 10^5$ we have $\\pi(x) = 9592$, while $x/\\ln x \\approx 8686$.\n",
    "\n",
    "**Exercise.**\n",
    "\n",
    "(a) Plot the ratio $\\pi(x) / (x / \\ln x)$ for $2 \\le x \\le 10^5$. Does the ratio approach $1$ quickly?\n",
    "\n",
    "(b) Add the function $\\operatorname{Li}(x) = \\int_2^x \\frac{dt}{\\ln t}$ to the first plot, approximating the integral by the sum `np.cumsum(1 / np.log(xs))`. Which approximation of $\\pi(x)$ is better?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c050",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c051",
   "metadata": {},
   "source": [
    "## Part C — optional challenges\n",
    "\n",
    "### C1. The digits of $\\sqrt{2}$, one by one ★★★\n",
    "\n",
    "For an integer $n \\ge 0$, the number $\\lfloor \\sqrt{n} \\rfloor$ is the largest integer $k$ such that $k^2 \\le n$. It can be found **without multiplication**, using $(k+1)^2 = k^2 + 2k + 1$:\n",
    "\n",
    "```text\n",
    "k ← 1, kw ← 1                 (invariant: kw = k²)\n",
    "while kw ≤ n:  kw ← kw + 2k + 1,  k ← k + 1\n",
    "return k − 1\n",
    "```\n",
    "\n",
    "**Exercise.**\n",
    "\n",
    "(a) Implement this procedure as `najw_kwadrat(n)` (for small $n$!) and compare it with `math.isqrt`.\n",
    "\n",
    "(b) Note that $\\lfloor 10^j \\sqrt{x} \\rfloor = \\lfloor \\sqrt{x \\cdot 10^{2j}} \\rfloor$. Write a generator `cyfry_pierwiastka(x)` that yields, in turn, $\\lfloor\\sqrt{x}\\rfloor, \\lfloor 10\\sqrt{x}\\rfloor, \\lfloor 100\\sqrt{x}\\rfloor, \\dots$, finding **one** new digit at each step (it suffices to try at most 10 candidates).\n",
    "\n",
    "(c) Examine the expansions of $\\sqrt{99}$, $\\sqrt{9999}$, $\\sqrt{999999}$ (e.g., `sympy.N(sympy.sqrt(9999), 30)`). What pattern do you see? Explain it using the expansion $\\sqrt{1 - \\varepsilon} = 1 - \\frac{\\varepsilon}{2} - \\frac{\\varepsilon^2}{8} - \\dots$"
   ]
  },
  {
   "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": [
    "### C2. The Tower of Hanoi ★★★\n",
    "\n",
    "We have three pegs and $n$ disks of different sizes, stacked on the first peg from the largest at the bottom to the smallest at the top. In one move we transfer one disk; a larger disk may never be placed on a smaller one. The goal is to move all the disks to the third peg.\n",
    "\n",
    "**Exercise.** (a) Write a recursive function `hanoi(n, z=1, przez=2, do=3)` (from, via, to) that returns the list of moves (pairs: from which peg to which). (b) Check that the number of moves is $2^n - 1$ for $n \\le 10$. (c) On paper, prove by induction that fewer moves do not suffice."
   ]
  },
  {
   "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": [
    "### C3. The number $e$ to 100 digits ★★★\n",
    "\n",
    "We have $e = \\sum_{k \\ge 0} \\frac{1}{k!}$. Compute $\\lfloor 10^{100} e \\rfloor$ using **integers only**. *Hint:* sum $\\lfloor 10^{100+G} / k! \\rfloor$ with a margin of a few guard digits $G$, and bound the tail of the series: $\\sum_{k > N} \\frac{1}{k!} < \\frac{1}{N! \\cdot N}$. Compare the result with the value from the `mpmath` library (it is installed together with SymPy): `mpmath.mp.dps = 110; print(mpmath.e)`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c056",
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "# TWÓJ KOD\n",
    "..."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c057",
   "metadata": {},
   "source": [
    "## Exercises for independent practice\n",
    "\n",
    "These exercises are for your own practice. Each exercise is **a single function** with exactly the given name and parameters, and you can check the given examples right away on your own computer. Rules:\n",
    "\n",
    "- the function must **return** its result (`return`) — do not use `input()`, and use `print()` only for local testing;\n",
    "- you may use the Python standard library (e.g., the `math` module) unless the exercise says otherwise.\n",
    "\n",
    "### Z1. Digital root ★\n",
    "\n",
    "Write a function `cyfrowy_pierwiastek(n)` that, for an integer $n \\ge 0$, returns its **digital root**: we add up the decimal digits of $n$, then the digits of the resulting sum, and so on, until a single-digit number remains.\n",
    "\n",
    "Examples: `cyfrowy_pierwiastek(2026) == 1` (since $2+0+2+6 = 10$ and $1+0 = 1$), `cyfrowy_pierwiastek(9875) == 2` ($29 \\to 11 \\to 2$), `cyfrowy_pierwiastek(0) == 0`.\n",
    "\n",
    "*Something to think about (not graded):* can you compute the result **without a loop**, with a single formula?\n",
    "\n",
    "### Z2. The worst case of the Euclidean algorithm ★★\n",
    "\n",
    "Write a function `lame(k)` that, for $k \\ge 1$, returns the pair `(a, b)` — the smallest pair of integers $a > b \\ge 1$ (smallest $a$ first, then the smallest $b$ for that value) for which the loop\n",
    "\n",
    "```python\n",
    "while b != 0:\n",
    "    a, b = b, a % b\n",
    "```\n",
    "\n",
    "runs **exactly** $k$ times. The function must be fast for $k \\le 100$ (searching through all pairs will not finish in time — use the observation from exercise B4).\n",
    "\n",
    "Examples: `lame(1) == (2, 1)`, `lame(3) == (5, 3)`.\n",
    "\n",
    "### Z3. Integer square root by Newton’s method ★★\n",
    "\n",
    "Write a function `isqrt_newton(n)` that, for an integer $n \\ge 0$, returns $\\lfloor \\sqrt{n} \\rfloor$ using **integer arithmetic only**. For $n = 0$, return $0$; for $n \\ge 1$, start from $x_0 = n$ and iterate\n",
    "\n",
    "$$x_{k+1} = \\left\\lfloor \\frac{x_k + \\lfloor n / x_k \\rfloor}{2} \\right\\rfloor,$$\n",
    "\n",
    "as long as the sequence decreases, i.e., as long as $x_{k+1} < x_k$. The result is the first term $x_k$ for which $x_{k+1} \\ge x_k$. Do not use `math.isqrt`, `math.sqrt`, `** 0.5`, or `float` numbers. The function must also work correctly for numbers with hundreds of digits.\n",
    "\n",
    "Examples: `isqrt_newton(17) == 4`, `isqrt_newton(10**100) == 10**50`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c058",
   "metadata": {},
   "outputs": [],
   "source": [
    "def cyfrowy_pierwiastek(n):\n",
    "    # TWÓJ KOD\n",
    "    ...\n",
    "\n",
    "def lame(k):\n",
    "    # TWÓJ KOD\n",
    "    ...\n",
    "\n",
    "def isqrt_newton(n):\n",
    "    # TWÓJ KOD\n",
    "    ...\n",
    "\n",
    "# Testy lokalne — odkomentuj, gdy funkcje będą gotowe:\n",
    "# assert cyfrowy_pierwiastek(2026) == 1 and cyfrowy_pierwiastek(9875) == 2 and cyfrowy_pierwiastek(0) == 0\n",
    "# assert lame(1) == (2, 1) and lame(3) == (5, 3)\n",
    "# assert isqrt_newton(17) == 4 and isqrt_newton(10**100) == 10**50\n",
    "# print(\"Testy przykładowe przechodzą.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c059",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "**Next session:** {doc}`lab02_sympy_sage` — first symbolic computations in SymPy and SageMath."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
