Lab 1: VS Code, Jupyter, and Python as a mathematician’s calculator#
Duration: 90 min · Lecture: Lecture 1 — working environment
Learning goals#
After this session you will be able to:
run a Jupyter notebook in Visual Studio Code with your own Python environment;
write Markdown cells with \(\LaTeX\) formulas, as well as code cells;
use Python’s arithmetic deliberately: integers of arbitrary length (
int), floating-point numbers (float), and exact fractions (Fraction), as well as the operators/,//,%,**;express simple mathematical algorithms with loops, conditionals, functions, and list comprehensions.
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).
How to work with this problem set
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.
0. Setting up the environment (≈ 15 min)#
Visual Studio Code — download it from https://code.visualstudio.com. In the Extensions panel (
Ctrl+Shift+X, on macOSCmd+Shift+X), install the Python and Jupyter extensions (publisher: Microsoft).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).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:python3 -m venv .venv # Windows: py -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate python -m pip install sympy numpy matplotlib ipykernel
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.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.
Detailed installation instructions (Windows, macOS, Linux): Working environment: VS Code, Python, Jupyter, SymPy, and SageMath.
import sys, platform
print("Python:", sys.version.split()[0], "|", platform.system())
try:
import sympy, numpy, matplotlib
print("SymPy:", sympy.__version__, "| NumPy:", numpy.__version__,
"| Matplotlib:", matplotlib.__version__)
except ImportError as e:
print("Brakuje pakietu:", e.name, "— zainstaluj go poleceniem: python -m pip install", e.name)
Python: 3.12.11 | Darwin
SymPy: 1.14.0 | NumPy: 2.5.3 | Matplotlib: 3.11.2
If the installation fails
Do not spend the session fighting the installation — work in the browser for now and finish installing at home:
the faculty’s JupyterHub server (for WMI UAM students): https://jupyter.wmi.amu.edu.pl,
CoCalc: https://cocalc.com (Python and SageMath in the browser),
SageMathCell: https://sagecell.sagemath.org (quick one-off computations).
Key notebook shortcuts (VS Code):
Shortcut |
Action |
|---|---|
|
run the cell and move to the next one |
|
run the cell and stay in it |
|
new cell above / below |
|
change the cell type to Markdown / code |
|
delete the cell |
|
VS Code command palette |
Part A — warm-up (≈ 20 min)#
A1. A Markdown cell with a formula ★#
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.
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
Exercise. Insert a new Markdown cell below (Esc, B, M) and write in it:
the formula for the roots of the quadratic equation \(ax^2 + bx + c = 0\) (with the discriminant \(\Delta\)),
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\),
the set \(\{\, d \in \mathbb{N} : d \mid 12 \,\}\) — list its elements.
A2. Integers have no length limit ★#
In Python, numbers of type int can be arbitrarily long — the only limit is the computer’s memory.
Let us compute \(2^{1000}\) and count the decimal digits of this number:
n = 2**1000
print(n)
print("liczba cyfr:", len(str(n)))
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
liczba cyfr: 302
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\).)
# TWÓJ KOD
...
The float type has a limited range and precision (about 16 significant digits):
print(2.0**1000)
1.0715086071862673e+301
Python printed the shortest decimal representation that uniquely determines this float number (here,
17 significant digits). The number \(2^{1000}\) itself, being a power of two, is stored exactly in the
float type, but neighboring float numbers in the interval \([2^{1000}, 2^{1001})\) are \(2^{948}\)
apart, so, for example, the number \(2^{1000} + 1\) can no longer be represented. The range is limited as
well: the largest finite float number is \((2-2^{-52})\cdot2^{1023}\approx1.8\cdot10^{308}\),
so \(2^{1024}\) lies outside it. Converting an integer that is too large into a float raises an
error:
float(2**1024) # liczba zbyt duża dla typu float → OverflowError
---------------------------------------------------------------------------
OverflowError Traceback (most recent call last)
Cell In[5], line 1
----> 1 float(2**1024) # liczba zbyt duża dla typu float → OverflowError
OverflowError: int too large to convert to float
The cell above fails on purpose. Read the error message — it is information, too!
A3. Division: /, //, % ★#
Python has three operators related to division: for integers, / always gives a result of type
float, // gives the integer quotient, and % the remainder. The function divmod returns the quotient and the remainder at once.
Let us try them on positive and negative numbers:
a, b = 17, 5
print(a / b, a // b, a % b, divmod(a, b))
print(-7 // 2, -7 % 2) # uwaga na liczby ujemne!
3.4 3 2 (3, 2)
-4 1
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
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!
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(...)).
# TWÓJ KOD: zamień ... na wyrażenie z all(...)
wynik = ...
print(wynik)
Analysis. Is such a check a proof of this identity for all integers? What would it take to prove it?
A4. A pitfall: ^ is not exponentiation ★#
In plain text (e.g., in an email) and in many programs, including SageMath, the power \(x^{10}\) is
written as x^10. In Python, this notation means something entirely different:
print(2 ** 10, 2 ^ 10) # potęga vs. XOR (alternatywa wykluczająca na bitach)
print(bin(2), bin(10), bin(2 ^ 10))
1024 8
0b10 0b1010 0b1000
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.
A5. Floating-point numbers: surprises ★#
Numbers of type float are represented in binary, so most decimal fractions can be stored only
approximately. Let us see what this implies even for the computation \(0.1 + 0.2\):
print(0.1 + 0.2 == 0.3)
print(0.1 + 0.2)
print(f"{0.1:.25f}")
print((0.1).as_integer_ratio()) # dokładna wartość przechowywana w pamięci
False
0.30000000000000004
0.1000000000000000055511151
(3602879701896397, 36028797018963968)
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 “Anatomy of a floating-point number” applet.
When exact computation is needed, we use fractions (Fraction); when an approximate result is enough, we compare float numbers with a tolerance (math.isclose):
from fractions import Fraction
import math
print(Fraction(1, 10) + Fraction(2, 10) == Fraction(3, 10)) # ułamki dokładne
print(Fraction(0.1)) # ułamek równy (dokładnie!) liczbie float 0.1
print(math.isclose(0.1 + 0.2, 0.3)) # porównanie z tolerancją
True
3602879701896397/36028797018963968
True
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).
(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.)
# TWÓJ KOD
...
Part B — main exercises (≈ 45 min)#
B1. Sets as list comprehensions ★#
Set-builder notation has a close relative in Python — the list comprehension:
Mathematics |
Python |
|---|---|
\(\{\, n^2 : n \in \mathbb{N},\ 1 \le n \le 10 \,\}\) |
|
\(\{\, p \le 100 : p \text{ is prime} \,\}\) |
|
\(\forall_{x \in A}\ \varphi(x)\) |
|
\(\exists_{x \in A}\ \varphi(x)\) |
|
We define the function czy_pierwsza from the table by trial division: a number \(n \ge 2\) is prime
if it is not divisible by any number \(d\) with \(2 \le d \le \lfloor\sqrt{n}\rfloor\) (if \(n = de\)
and \(2 \le d \le e\), then \(d \le \sqrt{n}\)). Let us list the primes less than \(100\):
from math import isqrt
def czy_pierwsza(n):
"""Czy n jest liczbą pierwszą? (dzielenie próbne do pierwiastka z n)"""
if n < 2:
return False
return all(n % d != 0 for d in range(2, isqrt(n) + 1))
pierwsze = [p for p in range(2, 101) if czy_pierwsza(p)]
print(pierwsze)
print(len(pierwsze), "liczb pierwszych mniejszych od 100")
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
25 liczb pierwszych mniejszych od 100
Exercise.
(a) Print the set \(P_1 = \{\, p < 200 : p \text{ prime},\ p \equiv 1 \pmod 4 \,\}\).
(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).
(c) For each \(p \in P_1\), print the representation \(p = a^2 + b^2\) with \(a \le b\).
# TWÓJ KOD
...
B2. Digits in an arbitrary base ★#
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\).
Exercise.
(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).
(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\).
(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?
def cyfry(n, b=10):
"""Lista cyfr liczby n >= 0 w bazie b, od najbardziej znaczącej."""
# TWÓJ KOD
...
def suma_cyfr(n, b=10):
# TWÓJ KOD
...
# Testy (odkomentuj, gdy funkcje będą gotowe):
# print(cyfry(2026, 2), bin(2026))
# print(cyfry(0), cyfry(255, 16), suma_cyfr(2**1000))
B3. The Collatz sequence ★#
For \(n \ge 1\), we define \(c_0 = n\) and
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.
Exercise.
(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].
(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).
(c) Find the \(n < 10{,}000\) with the longest trajectory (you should get \(261\) steps).
(d) Draw a scatter plot of \(n \mapsto\) collatz_dlugosc(n) for \(n < 10{,}000\) (plt.scatter(..., s=1)).
import matplotlib.pyplot as plt
def collatz(n):
# TWÓJ KOD
...
def collatz_dlugosc(n):
# TWÓJ KOD
...
# print(collatz(6), collatz_dlugosc(27))
B4. The Euclidean algorithm and Fibonacci numbers ★★#
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:
while b != 0:
a, b = b, a % b
Exercise.
(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).
(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\).
(c) What numbers do you see? Formulate a conjecture.
(d) How fast do these numbers grow? Compute the ratios of consecutive values of \(a\).
import math, random
def nwd_kroki(a, b):
# TWÓJ KOD
...
# print(nwd_kroki(1071, 462)) # oczekiwane: (21, 3)
Lamé’s theorem (1844)
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.
B5. Square roots by Heron’s method ★★#
To approximate \(\sqrt{a}\) for \(a > 0\), we start from \(x_0 > 0\) and iterate
This is a special case of Newton’s method for \(f(x) = x^2 - a\) — we will return to it later in the course.
Exercise.
(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?
(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?
(c) Analysis: why does the error in (a) stop decreasing at roughly the \(10^{-16}\) level?
# TWÓJ KOD
...
B6. Divisors and perfect numbers ★#
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\).
Exercise.
(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?
(b) Find all perfect numbers \(n \le 10{,}000\).
(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\)).
(d) The numbers \(220\) and \(284\) are amicable: the sum of the proper divisors of each of them equals the other. Check this.
Fun fact: it is still unknown whether an odd perfect number exists.
def dzielniki(n):
# TWÓJ KOD
...
# print(dzielniki(28)) # oczekiwane: [1, 2, 4, 7, 14, 28]
B7. Pythagorean triples ★#
Exercise.
(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?
(b) Select the primitive triples, i.e., those with \(\gcd(a, b) = 1\).
(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).
# TWÓJ KOD
...
B8. The sieve of Eratosthenes and timing ★★#
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.
Exercise.
(a) Write a function sito(n) that returns the list of primes \(\le n\) (use a list of Boolean values [True] * (n + 1)).
(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\).
(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()).
import time
def sito(n):
# TWÓJ KOD
...
B9. How many primes are there? A first plot ★#
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).
import numpy as np
import matplotlib.pyplot as plt
N = 100_000
sito_np = np.ones(N + 1, dtype=bool)
sito_np[:2] = False
for p in range(2, int(N**0.5) + 1):
if sito_np[p]:
sito_np[p*p::p] = False
pi_x = np.cumsum(sito_np) # pi_x[x] = liczba liczb pierwszych <= x
xs = np.arange(2, N + 1)
plt.figure(figsize=(8, 4))
plt.plot(xs, pi_x[2:], label=r"$\pi(x)$")
plt.plot(xs, xs / np.log(xs), label=r"$x/\ln x$")
plt.xlabel("$x$"); plt.legend(); plt.title("Liczby pierwsze do $10^5$")
plt.show()
Both curves grow similarly, and from \(x = 17\) on, the curve \(x/\ln x\) stays below \(\pi(x)\) (J. B. Rosser, L. Schoenfeld, 1962): at \(x = 10^5\) we have \(\pi(x) = 9592\), while \(x/\ln x \approx 8686\).
Exercise.
(a) Plot the ratio \(\pi(x) / (x / \ln x)\) for \(2 \le x \le 10^5\). Does the ratio approach \(1\) quickly?
(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?
# TWÓJ KOD
...
Part C — optional challenges#
C1. The digits of \(\sqrt{2}\), one by one ★★★#
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\):
k ← 1, kw ← 1 (invariant: kw = k²)
while kw ≤ n: kw ← kw + 2k + 1, k ← k + 1
return k − 1
Exercise.
(a) Implement this procedure as najw_kwadrat(n) (for small \(n\)!) and compare it with math.isqrt.
(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).
(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\)
# TWÓJ KOD
...
C2. The Tower of Hanoi ★★★#
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.
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.
# TWÓJ KOD
...
C3. The number \(e\) to 100 digits ★★★#
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).
# TWÓJ KOD
...
Exercises for independent practice#
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:
the function must return its result (
return) — do not useinput(), and useprint()only for local testing;you may use the Python standard library (e.g., the
mathmodule) unless the exercise says otherwise.
Z1. Digital root ★#
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.
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.
Something to think about (not graded): can you compute the result without a loop, with a single formula?
Z2. The worst case of the Euclidean algorithm ★★#
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
while b != 0:
a, b = b, a % b
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).
Examples: lame(1) == (2, 1), lame(3) == (5, 3).
Z3. Integer square root by Newton’s method ★★#
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
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.
Examples: isqrt_newton(17) == 4, isqrt_newton(10**100) == 10**50.
def cyfrowy_pierwiastek(n):
# TWÓJ KOD
...
def lame(k):
# TWÓJ KOD
...
def isqrt_newton(n):
# TWÓJ KOD
...
# Testy lokalne — odkomentuj, gdy funkcje będą gotowe:
# assert cyfrowy_pierwiastek(2026) == 1 and cyfrowy_pierwiastek(9875) == 2 and cyfrowy_pierwiastek(0) == 0
# assert lame(1) == (2, 1) and lame(3) == (5, 3)
# assert isqrt_newton(17) == 4 and isqrt_newton(10**100) == 10**50
# print("Testy przykładowe przechodzą.")
Next session: Lab 2: SymPy and SageMath — first symbolic computations — first symbolic computations in SymPy and SageMath.