From e30aad0fd9dd74e075b63e64535f6bd77711d0e1 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Sun, 19 Dec 2021 16:00:11 +0100 Subject: [PATCH 01/45] Create continued-fractions.md Initial text --- src/algebra/continued-fractions.md | 57 ++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/algebra/continued-fractions.md diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md new file mode 100644 index 000000000..deb548e7a --- /dev/null +++ b/src/algebra/continued-fractions.md @@ -0,0 +1,57 @@ + +# Continued fractions in competitive programming + +**Continued fraction** is a way of representing arbitrary real number as a convergent sequence of rational numbers. What makes them important and useful in competitive programming is the fact that each consequent fraction is, in a way, the best possible approximation of the specified real number. Besides that, continued fractions are closely related to euclidean algorithm which makes them useful in a bunch of number-theoretical problems. + +## Definitions + +### Continued fractions representation + +Any real number $r$ may be uniquely represented as $r = a_0 + \frac{1}{q_0}$ where $a_0 = \lfloor r \rfloor$ and $q_0$ is either infinite (meaning $r$ is an integer) or is a real number greater than $1$. Expanding it indefinitely, one obtains an infinite representation + +$$r=a_0 + \frac{1}{a_1 + \frac{1}{a_2+\dots}}$$ + +Which is shortly denoted as $r=[a_0, a_1, \dots]$. For consistency, we will define infinity representation as $\infty = [\infty, \infty, \dots]$ and, therefore, rational numbers can be distinguished from irrational by the fact that their continued fraction representation always ends with a sequence of infinities. For example, + +$$\frac{5}{3} = 1 + \frac{1}{1+\frac{1}{2+\frac{1}{\infty}}} = [1,1,2,\infty,\infty,\dots]$$ + +For shortness we will drop the infinite part in the expansion of rational numbers, thus $\frac{5}{3}=[1,1,2]$. Note that $[1,1,1,1]$ would represent the same rational number, but it can not be obtained through floor operation. + +Generally, it can be proven that there is unique way to represent any irrational number as continued fraction and there are exactly two ways to represent any rational number, which are $[a_0, \dots, a_k]$ and $[a_0, \dots, a_k-1, 1]$. We will almost always stick to the first one, as it is consistent with the floor-defined fractions. + +#### Implementation + +In the code snippets we will mostly assume that we work with the finite continued fractions. Although they're defined recursively it will prove more useful to construct them iteratively. If we start with $r=\frac{p}{q}$, the transition looks like + +$$r =\left\lfloor \frac p q \right\rfloor + \frac{1}{\left(\frac{p}{q}-\left\lfloor \frac{p}{q}\right\rfloor\right)^{-1}}$$ + +On the other hand, the denominator may be rewritten as + +$$\frac{p}{q}-\left\lfloor \frac{p}{q}\right\rfloor = \frac{p-q\cdot \lfloor \frac{p}{q} \rfloor}{q} = \frac{p \bmod q}{q}$$ + +Therefore, computation of a continued fraction representation for $r=\frac{p}{q}$ follows the same steps the Euclid algorithm for $p$ and $q$ does. + + +```cpp +struct fraction { + vector a; + + fraction():a{0}{} + + // Assuming 0 <= p and 0 < q + fraction(int p, int q) { + while(q) { + a.push_back(p / q); + p %= q; + swap(p, q); + } + } +} +``` + +### Convergents + +Now that we defined both finite and infinite continued fraction representations, let's define convergent sequence which corresponds to real numbers. For the number $r=[a_0, a_1, a_2, \dots]$, its convergent sequence is defined as + +$$r_0=[a_0],\\r_1=[a_0, a_1],\\ \dots,\\ r_k=[a_0, a_1, \dots, a_k].$$ + From 25bcd4990c3bb28f394b4e12c601ab3911d4632c Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Sun, 19 Dec 2021 16:51:06 +0100 Subject: [PATCH 02/45] Update continued-fractions.md info on convergents --- src/algebra/continued-fractions.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index deb548e7a..84b47fa4f 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -55,3 +55,21 @@ Now that we defined both finite and infinite continued fraction representations, $$r_0=[a_0],\\r_1=[a_0, a_1],\\ \dots,\\ r_k=[a_0, a_1, \dots, a_k].$$ +It is very important to understand how these rational numbers are constructed and how do they relate with the underlying number $r$. For now, it is clear that the numerator and denominator of $r_k$ are polynomials of $a_0, a_1, \dots, a_k$. Moreover, this polynomials only depend on the number of variables $k$, that is + +$$r_k = \frac{P_k(a_0, a_1, \dots, a_k)}{Q_k(a_0,a_1, \dots, a_k)}$$ + +On the other hand, it is clear that + +$$r_k = a_0 + \frac{1}{[a_1,\dots, a_k]}=\frac{a_0 P_{k-1}(a_1, \dots, a_k) + Q_{k-1}(a_1, \dots, a_k)}{P_{k-1}(a_1, \dots, a_k)}$$ + +This gives us the relationship $Q_k(a_0, \dots, a_k) = P_{k-1}(a_1, \dots, a_k)$. Therefore, we can focus on the numerator polynomials, as the denominator polynomials can be derived from them. This leads us to the relationship + +$$P_k(a_0, \dots, a_k) = a_0 P_{k-1}(a_1, \dots, a_k) + P_{k-2}(a_2, \dots, a_k)$$ + +We already know that $r_0 = \frac{a_0}{1}$ and $r_1 = \frac{a_0 a_1 + 1}{a_1}$, which means that + +$$P_0(a_0)=a_0,\\ P_1(a_0, a_1) = a_0 a_1 + 1$$ + +For consistency with this rule it is also convenient to define $P_{-1} = 1$ and $P_{-2}=0$, which also implies implicit starting point $r_{-1} = \frac{1}{0}$. + From 270ffbadeaa6103738cf663de4c67ba7c3e25c17 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Sun, 19 Dec 2021 17:17:21 +0100 Subject: [PATCH 03/45] Update continued-fractions.md +continuant and mediant expression --- src/algebra/continued-fractions.md | 31 ++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 84b47fa4f..7b22589ac 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -73,3 +73,34 @@ $$P_0(a_0)=a_0,\\ P_1(a_0, a_1) = a_0 a_1 + 1$$ For consistency with this rule it is also convenient to define $P_{-1} = 1$ and $P_{-2}=0$, which also implies implicit starting point $r_{-1} = \frac{1}{0}$. +#### Continuant + +It is a well-known fact in numerical analysis that the determinant of an arbitrary tridiagonal matrix + +$$T_k = \det \begin{bmatrix} +a_0 & b_0 & 0 & \dots & 0 \\ +c_0 & a_1 & b_1 & \dots & 0 \\ +0 & c_1 & a_2 & . & \vdots \\ +\vdots & \vdots & . & \ddots & c_{k-1} \\ +0 & 0 & \dots & b_{k-1} & a_k +\end{bmatrix}$$ + +can be computed recursively as $T_k = a_k T_{k-1} - b_{k-1} c_{k-1} T_{k-2}$. Applying this result to $P_k$ yields a direct expression + +$$P_k = \det \begin{bmatrix} +x_k & 1 & 0 & \dots & 0 \\ +-1 & x_{k-1} & 1 & \dots & 0 \\ +0 & -1 & x_2 & . & \vdots \\ +\vdots & \vdots & . & \ddots & 1 \\ +0 & 0 & \dots & -1 & x_0 +\end{bmatrix}$$ + +This polynomial is also known as [the continuant](https://en.wikipedia.org/wiki/Continuant_(mathematics)) due to its close relation with continued fraction. The determinant representation also immediately gives us the alternative formula for computing continuants as + +$$P_k(a_0, \dots, a_k) = a_k P_{k-1}(a_0, \dots, a_{k-1}) + P_{k-2}(a_0, \dots, a_{k-2})$$ + +This formula is of extreme convenience to us, because it shows that the $r_k = \frac{p_k}{q_k}$, in fact, can be computed as + +$$\frac{p_k}{q_k} = \frac{a_k p_{k-1} + p_{k-2}}{a_k q_{k-1} + q_{k-2}}$$ + +Meaning that $r_k$ is a weighted [mediant](https://en.wikipedia.org/wiki/Mediant_(mathematics)) of $r_{k-1}$ and $r_{k-2}$. From dc11f226670ef8a7e0071893de8a4650b414479f Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Sun, 19 Dec 2021 18:13:02 +0100 Subject: [PATCH 04/45] Update continued-fractions.md convergence info --- src/algebra/continued-fractions.md | 35 ++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 7b22589ac..6c7e6c521 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -104,3 +104,38 @@ This formula is of extreme convenience to us, because it shows that the $r_k = \ $$\frac{p_k}{q_k} = \frac{a_k p_{k-1} + p_{k-2}}{a_k q_{k-1} + q_{k-2}}$$ Meaning that $r_k$ is a weighted [mediant](https://en.wikipedia.org/wiki/Mediant_(mathematics)) of $r_{k-1}$ and $r_{k-2}$. + +## Convergence + +Now that we have some explicit formulas for convergent numbers, let's estimate their distance to the final number $r$. First of all, we can estimate the difference between adjacent convergents: + +$$\frac{p_k}{q_k} - \frac{p_{k-1}}{q_{k-1}} = \frac{p_k q_{k-1} - p_{k-1} q_k}{q_k q_{k-1}}$$ + +For the numerator of this fraction, it is possible to get rid of numbers with index $k$: + +$$\begin{align} p_k q_{k-1} - p_{k-1} q_k &= (a_k p_{k-1} + p_{k-2}) q_{k-1} - p_{k-1} (a_k q_{k-1} + q_{k-2}) +\\&= p_{k-2} q_{k-1} - p_{k-1} q_{k-2}\end{align}$$ + +Thus, the numerator of $r_k - r_{k-1}$ is always the opposite to the numerator of $r_{k-1} - r_{k-2}$. It is equal to $1$ for $a_1 - a_0$, therefore + +$$r_k - r_{k-1} = \frac{(-1)^{k-1}}{q_k q_{k-1}}$$ + + +This allows for alternative representation of $r_k$ as a partial sum of infinite series: + +$$r_k = (r_k - r_{k-1}) + \dots + (r_1 - r_0) + r_0 += a_0 + \sum\limits_{i=1}^k \frac{(-1)^{i-1}}{q_i q_{i-1}}$$ + +By definition, $q_k$ monotonically increases at least as fast as Fibonacci numbers, thus + +$$r = \lim\limits_{k \to \infty} r_k = a_0 + \sum\limits_{i=1}^\infty \frac{(-1)^{i-1}}{q_i q_{i-1}}$$ + +is always well-defined. Noteworthy, the residual series + +$$r-r_k = \sum\limits_{i=k+1}^\infty \frac{(-1)^{i-1}}{q_i q_{i-1}}$$ + +always has the same sign as $(-1)^k$ due to how fast $q_i q_{i-1}$ decreases. It means that even-indexed $r_k$ monotonously approach $r$ from below while odd-indexed $r_k$ monotonously approach it from above: + +
+![Convergence towards underlying number](https://codeforces.com/predownloaded/ca/8d/ca8d8835864ccccea90e458e3d8fa840a6143c13.gif) +
From 81d1ebc7f3c4538e4525d87c97c5b3fc4cbd2583 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Sun, 19 Dec 2021 18:19:05 +0100 Subject: [PATCH 05/45] Update continued-fractions.md fix --- src/algebra/continued-fractions.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 6c7e6c521..f14372929 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -139,3 +139,7 @@ always has the same sign as $(-1)^k$ due to how fast $q_i q_{i-1}$ decreases. It
![Convergence towards underlying number](https://codeforces.com/predownloaded/ca/8d/ca8d8835864ccccea90e458e3d8fa840a6143c13.gif)
+ +From this picture we can see that, in fact, distance between $r$ and $r_k$ is never larger than the distance between $r_k$ and $r_{k+1}$, therefore + +$$\left|r-\frac{p_k}{q_k}\right| \leq \frac{1}{q_k q_{k+1}} \leq \frac{1}{q_k^2}$$ From 7012fbc692d9820a29b5236dd0fd628f0b2e54ac Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Mon, 20 Dec 2021 14:59:08 +0100 Subject: [PATCH 06/45] Update continued-fractions.md style + minor fixes --- src/algebra/continued-fractions.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index f14372929..5f34ff8dd 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -1,7 +1,7 @@ # Continued fractions in competitive programming -**Continued fraction** is a way of representing arbitrary real number as a convergent sequence of rational numbers. What makes them important and useful in competitive programming is the fact that each consequent fraction is, in a way, the best possible approximation of the specified real number. Besides that, continued fractions are closely related to euclidean algorithm which makes them useful in a bunch of number-theoretical problems. +**Continued fraction** is a way of representing arbitrary real number as a convergent sequence of rational numbers. What makes them important and useful in competitive programming is the fact that each consequent fraction is, in a way, the best possible approximation of the specified real number. Besides that, continued fractions are closely related to Euclidean algorithm which makes them useful in a bunch of number-theoretical problems. ## Definitions @@ -11,25 +11,25 @@ Any real number $r$ may be uniquely represented as $r = a_0 + \frac{1}{q_0}$ whe $$r=a_0 + \frac{1}{a_1 + \frac{1}{a_2+\dots}}$$ -Which is shortly denoted as $r=[a_0, a_1, \dots]$. For consistency, we will define infinity representation as $\infty = [\infty, \infty, \dots]$ and, therefore, rational numbers can be distinguished from irrational by the fact that their continued fraction representation always ends with a sequence of infinities. For example, +Which is shortly denoted as $r=[a_0, a_1, \dots]$. For consistency, infinity representation is defined in this article as $\infty = [\infty, \infty, \dots]$. Therefore, rational numbers can be distinguished from irrational by the fact that their continued fraction representation always ends with a sequence of infinities. For example, $$\frac{5}{3} = 1 + \frac{1}{1+\frac{1}{2+\frac{1}{\infty}}} = [1,1,2,\infty,\infty,\dots]$$ -For shortness we will drop the infinite part in the expansion of rational numbers, thus $\frac{5}{3}=[1,1,2]$. Note that $[1,1,1,1]$ would represent the same rational number, but it can not be obtained through floor operation. +We will drop the infinite part of the expansion of rational numbers for shortness, thus $\frac{5}{3}=[1,1,2]$. -Generally, it can be proven that there is unique way to represent any irrational number as continued fraction and there are exactly two ways to represent any rational number, which are $[a_0, \dots, a_k]$ and $[a_0, \dots, a_k-1, 1]$. We will almost always stick to the first one, as it is consistent with the floor-defined fractions. +Note that $[1,1,1,1]$ would also represent $\frac 5 3$. Generally, it can be proven that there is unique way to represent any irrational number and there are exactly two ways to represent any rational number, which are $[a_0, \dots, a_k]$ and $[a_0, \dots, a_k-1, 1]$. We will almost always stick to the first one, as it is consistent with the way continued fractions were defined for irrational numbers. #### Implementation -In the code snippets we will mostly assume that we work with the finite continued fractions. Although they're defined recursively it will prove more useful to construct them iteratively. If we start with $r=\frac{p}{q}$, the transition looks like +In the code snippets we will mostly assume that we work with the finite continued fractions. Although continued fractions defined recursively it is more efficient to construct them iteratively. If we start with $r=\frac{p}{q}$, the transition looks like $$r =\left\lfloor \frac p q \right\rfloor + \frac{1}{\left(\frac{p}{q}-\left\lfloor \frac{p}{q}\right\rfloor\right)^{-1}}$$ -On the other hand, the denominator may be rewritten as +The denominator part of this expression may be rewritten as $$\frac{p}{q}-\left\lfloor \frac{p}{q}\right\rfloor = \frac{p-q\cdot \lfloor \frac{p}{q} \rfloor}{q} = \frac{p \bmod q}{q}$$ -Therefore, computation of a continued fraction representation for $r=\frac{p}{q}$ follows the same steps the Euclid algorithm for $p$ and $q$ does. +Thus, computation of a continued fraction representation for $r=\frac{p}{q}$ follows the same steps as the Euclidean algorithm for $p$ and $q$. ```cpp @@ -46,7 +46,7 @@ struct fraction { swap(p, q); } } -} +}; ``` ### Convergents From d161533716268b9595c6e1484786542593a591df Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Mon, 20 Dec 2021 17:35:29 +0100 Subject: [PATCH 07/45] Update continued-fractions.md style --- src/algebra/continued-fractions.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 5f34ff8dd..b6473555c 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -51,19 +51,19 @@ struct fraction { ### Convergents -Now that we defined both finite and infinite continued fraction representations, let's define convergent sequence which corresponds to real numbers. For the number $r=[a_0, a_1, a_2, \dots]$, its convergent sequence is defined as +Now that both finite and infinite continued fraction representations are defined, let's define convergent sequence which corresponds the underlying real number. For the number $r=[a_0, a_1, a_2, \dots]$, its convergent sequence is defined as $$r_0=[a_0],\\r_1=[a_0, a_1],\\ \dots,\\ r_k=[a_0, a_1, \dots, a_k].$$ -It is very important to understand how these rational numbers are constructed and how do they relate with the underlying number $r$. For now, it is clear that the numerator and denominator of $r_k$ are polynomials of $a_0, a_1, \dots, a_k$. Moreover, this polynomials only depend on the number of variables $k$, that is +Each individual rational number $r_k$ is called the convergent of $r$. It is important to understand how these rational numbers are constructed and how they relate with the underlying number $r$. The numerator and denominator of $r_k$ are polynomials of $a_0, a_1, \dots, a_k$. These polynomials only depend on the number of variables $k$, that is $$r_k = \frac{P_k(a_0, a_1, \dots, a_k)}{Q_k(a_0,a_1, \dots, a_k)}$$ -On the other hand, it is clear that +On the other hand, $$r_k = a_0 + \frac{1}{[a_1,\dots, a_k]}=\frac{a_0 P_{k-1}(a_1, \dots, a_k) + Q_{k-1}(a_1, \dots, a_k)}{P_{k-1}(a_1, \dots, a_k)}$$ -This gives us the relationship $Q_k(a_0, \dots, a_k) = P_{k-1}(a_1, \dots, a_k)$. Therefore, we can focus on the numerator polynomials, as the denominator polynomials can be derived from them. This leads us to the relationship +This gives us the relationship $Q_k(a_0, \dots, a_k) = P_{k-1}(a_1, \dots, a_k)$. Therefore, we can focus on the numerator polynomials, as the denominator polynomials can be derived from them. This leads us to the relation $$P_k(a_0, \dots, a_k) = a_0 P_{k-1}(a_1, \dots, a_k) + P_{k-2}(a_2, \dots, a_k)$$ @@ -71,7 +71,7 @@ We already know that $r_0 = \frac{a_0}{1}$ and $r_1 = \frac{a_0 a_1 + 1}{a_1}$, $$P_0(a_0)=a_0,\\ P_1(a_0, a_1) = a_0 a_1 + 1$$ -For consistency with this rule it is also convenient to define $P_{-1} = 1$ and $P_{-2}=0$, which also implies implicit starting point $r_{-1} = \frac{1}{0}$. +For consistency, it is also convenient to define $P_{-1} = 1$ and $P_{-2}=0$, which implies starting points $r_{-1} = \frac{1}{0}$ and $r_{-2}=\frac{0}{1}$. #### Continuant @@ -95,15 +95,15 @@ x_k & 1 & 0 & \dots & 0 \\ 0 & 0 & \dots & -1 & x_0 \end{bmatrix}$$ -This polynomial is also known as [the continuant](https://en.wikipedia.org/wiki/Continuant_(mathematics)) due to its close relation with continued fraction. The determinant representation also immediately gives us the alternative formula for computing continuants as +This polynomial is also known as [the continuant](https://en.wikipedia.org/wiki/Continuant_(mathematics)) due to its close relation with continued fraction. Noteworthy, the determinant of such matrix won't change if the sequence on the main diagonal is reversed. This gives us the alternative formula to compute continuants: $$P_k(a_0, \dots, a_k) = a_k P_{k-1}(a_0, \dots, a_{k-1}) + P_{k-2}(a_0, \dots, a_{k-2})$$ -This formula is of extreme convenience to us, because it shows that the $r_k = \frac{p_k}{q_k}$, in fact, can be computed as +This representation is way more convenient, as it shows that $r_k = \frac{p_k}{q_k}$ can be computed as $$\frac{p_k}{q_k} = \frac{a_k p_{k-1} + p_{k-2}}{a_k q_{k-1} + q_{k-2}}$$ -Meaning that $r_k$ is a weighted [mediant](https://en.wikipedia.org/wiki/Mediant_(mathematics)) of $r_{k-1}$ and $r_{k-2}$. +Thus, $r_k$ is a weighted [mediant](https://en.wikipedia.org/wiki/Mediant_(mathematics)) of $r_{k-1}$ and $r_{k-2}$. ## Convergence From b7222823052e107580fb43ec2803a321a4b0786f Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Tue, 21 Dec 2021 13:16:14 +0100 Subject: [PATCH 08/45] Update continued-fractions.md starting on geometric interpretation --- src/algebra/continued-fractions.md | 35 ++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index b6473555c..f6a7b2b5c 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -105,6 +105,41 @@ $$\frac{p_k}{q_k} = \frac{a_k p_{k-1} + p_{k-2}}{a_k q_{k-1} + q_{k-2}}$$ Thus, $r_k$ is a weighted [mediant](https://en.wikipedia.org/wiki/Mediant_(mathematics)) of $r_{k-1}$ and $r_{k-2}$. +## Geometric interpretation + +If convergents $r_0, r_1, \dots$ are treated as 2-dimensional vectors $\vec r_k=(p_k;q_k)$, the mediant formula above turns into + +$$\vec r_k = a_k \vec r_{k-1} + \vec r_{k-2}.$$ + +To better understand geometric meaning of $\vec r_k$ we need to look closer into computation of $a_k$. Previously we investigated _convergents_ $r_k = [a_0, a_1, \dots, a_k]$. Let's now look on _residuals_ $s_k = [a_{k}, a_{k+1}, \dots]$. From their definition it holds that + +$$\left.s_k = a_{k} + \frac{1}{s_{k+1}}\right._{\textstyle .}$$ + +Starting with $s_0=r$, it is possible to derive similar recurrent formulas for $s_k=\frac{b_k}{c_k}$: + +$$\left.\frac{b_k}{c_k}=a_k + \frac{c_{k+1}}{b_{k+1}}\right._{\textstyle .}$$ + +Thus, $b_{k+1}=c_k$ and $c_{k+1} = b_k - c_k a_k = c_{k-1} - c_k a_k$. This expression looks very close to the continuant and from the starting points $s_0=\frac{r}{1}$ and $s_1 = \frac{1}{r-a_0}$ one may derive the explicit formula for $c_k$: + +$$c_k = P_{k-1}(r-a_0, -a_1, \dots, -a_{k-1}).$$ + +Taking into consideration the continuant properties (which follow from its determinant representation) + +$$\begin{align} +P_k(a_0, \dots, a_k) &= (-1)^{k+1} P_k(-a_0, \dots, -a_k),\\ +P_k(a_0, \dots, a_k) &= a_0 P_{k-1}(a_1, \dots, a_k) + P_{k-2}(a_2, \dots, a_k), +\end{align}$$ + +we may rearrange the expression for $c_k$ in a much simpler manner: + +$$c_k = (-1)^{k-1} (r q_{k-1} - p_{k-1}).$$ + +This gives us the final formula to calculate residual $s_k$ from convergents: + +$$s_k = \left|\frac{rq_{k-2} - p_{k-2}}{rq_{k-1} - p_{k-1}}\right|_{\textstyle .}$$ + +On the other hand, $a_k$ may be defined as $a_k = \lfloor s_k \rfloor$, thus we have more explicit expression for $a_k$ as well. + ## Convergence Now that we have some explicit formulas for convergent numbers, let's estimate their distance to the final number $r$. First of all, we can estimate the difference between adjacent convergents: From 94f29139ea04d999d2f4432b21dd6bdbf22ad10d Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Tue, 21 Dec 2021 13:31:38 +0100 Subject: [PATCH 09/45] Update continued-fractions.md style --- src/algebra/continued-fractions.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index f6a7b2b5c..0e1e01e65 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -5,29 +5,29 @@ ## Definitions -### Continued fractions representation +### Continued fraction representation -Any real number $r$ may be uniquely represented as $r = a_0 + \frac{1}{q_0}$ where $a_0 = \lfloor r \rfloor$ and $q_0$ is either infinite (meaning $r$ is an integer) or is a real number greater than $1$. Expanding it indefinitely, one obtains an infinite representation +Any real number $r$ may be uniquely represented as $r = a_0 + \frac{1}{q_0}$ where $a_0 = \lfloor r \rfloor$ and $q_0$ is either infinite (meaning $r$ is an integer) or is a real number greater than $1$. Expanding it indefinitely, one obtains the so-called continued fraction representation -$$r=a_0 + \frac{1}{a_1 + \frac{1}{a_2+\dots}}$$ +$$r=a_0 + \frac{1}{a_1 + \frac{1}{a_2+\dots}},$$ -Which is shortly denoted as $r=[a_0, a_1, \dots]$. For consistency, infinity representation is defined in this article as $\infty = [\infty, \infty, \dots]$. Therefore, rational numbers can be distinguished from irrational by the fact that their continued fraction representation always ends with a sequence of infinities. For example, +which is shortly denoted as $r=[a_0, a_1, \dots]$.For consistency, the representation of the infinity is defined here as $\infty = [\infty, \infty, \dots]$. Therefore, rational numbers can be distinguished from irrational by the fact that their continued fraction representation always ends with a sequence of infinities. For example, -$$\frac{5}{3} = 1 + \frac{1}{1+\frac{1}{2+\frac{1}{\infty}}} = [1,1,2,\infty,\infty,\dots]$$ +$$\frac{5}{3} = 1 + \frac{1}{1+\frac{1}{2+\frac{1}{\infty}}} = [1,1,2,\infty,\infty,\dots].$$ We will drop the infinite part of the expansion of rational numbers for shortness, thus $\frac{5}{3}=[1,1,2]$. -Note that $[1,1,1,1]$ would also represent $\frac 5 3$. Generally, it can be proven that there is unique way to represent any irrational number and there are exactly two ways to represent any rational number, which are $[a_0, \dots, a_k]$ and $[a_0, \dots, a_k-1, 1]$. We will almost always stick to the first one, as it is consistent with the way continued fractions were defined for irrational numbers. +Note that $[1,1,1,1]$, if treated as continued fraction, would also represent $\frac 5 3$. Generally, there is a unique way to represent any irrational number and there are exactly two ways to represent any rational number, which are $[a_0, \dots, a_k]$ and $[a_0, \dots, a_k-1, 1]$. We will stick to the first one, as it is consistent with the way continued fractions were defined for irrational numbers through flooring. #### Implementation In the code snippets we will mostly assume that we work with the finite continued fractions. Although continued fractions defined recursively it is more efficient to construct them iteratively. If we start with $r=\frac{p}{q}$, the transition looks like -$$r =\left\lfloor \frac p q \right\rfloor + \frac{1}{\left(\frac{p}{q}-\left\lfloor \frac{p}{q}\right\rfloor\right)^{-1}}$$ +$$r =\left\lfloor \frac p q \right\rfloor + \frac{1}{\left(\frac{p}{q}-\left\lfloor \frac{p}{q}\right\rfloor\right)^{-1}}.$$ The denominator part of this expression may be rewritten as -$$\frac{p}{q}-\left\lfloor \frac{p}{q}\right\rfloor = \frac{p-q\cdot \lfloor \frac{p}{q} \rfloor}{q} = \frac{p \bmod q}{q}$$ +$$\left(\frac{p}{q}-\left\lfloor \frac{p}{q}\right\rfloor\right)^{-1} = \frac{q}{p-q\cdot \lfloor \frac{p}{q} \rfloor} = \frac{q}{p \bmod q}.$$ Thus, computation of a continued fraction representation for $r=\frac{p}{q}$ follows the same steps as the Euclidean algorithm for $p$ and $q$. From e64b1b3528d9c9c950207841e3a3f9a2cedb89f0 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Tue, 21 Dec 2021 13:41:03 +0100 Subject: [PATCH 10/45] Update continued-fractions.md style --- src/algebra/continued-fractions.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 0e1e01e65..cb634730b 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -57,19 +57,19 @@ $$r_0=[a_0],\\r_1=[a_0, a_1],\\ \dots,\\ r_k=[a_0, a_1, \dots, a_k].$$ Each individual rational number $r_k$ is called the convergent of $r$. It is important to understand how these rational numbers are constructed and how they relate with the underlying number $r$. The numerator and denominator of $r_k$ are polynomials of $a_0, a_1, \dots, a_k$. These polynomials only depend on the number of variables $k$, that is -$$r_k = \frac{P_k(a_0, a_1, \dots, a_k)}{Q_k(a_0,a_1, \dots, a_k)}$$ +$$r_k = \frac{P_k(a_0, a_1, \dots, a_k)}{Q_k(a_0,a_1, \dots, a_k)}.$$ On the other hand, -$$r_k = a_0 + \frac{1}{[a_1,\dots, a_k]}=\frac{a_0 P_{k-1}(a_1, \dots, a_k) + Q_{k-1}(a_1, \dots, a_k)}{P_{k-1}(a_1, \dots, a_k)}$$ +$$r_k = a_0 + \frac{1}{[a_1,\dots, a_k]}=\frac{a_0 P_{k-1}(a_1, \dots, a_k) + Q_{k-1}(a_1, \dots, a_k)}{P_{k-1}(a_1, \dots, a_k)}.$$ -This gives us the relationship $Q_k(a_0, \dots, a_k) = P_{k-1}(a_1, \dots, a_k)$. Therefore, we can focus on the numerator polynomials, as the denominator polynomials can be derived from them. This leads us to the relation +This gives us the relation $Q_k(a_0, \dots, a_k) = P_{k-1}(a_1, \dots, a_k)$. Therefore, we can focus on the numerator polynomials, as the denominator polynomials can be derived from them. This leads us to the relation -$$P_k(a_0, \dots, a_k) = a_0 P_{k-1}(a_1, \dots, a_k) + P_{k-2}(a_2, \dots, a_k)$$ +$$P_k(a_0, \dots, a_k) = a_0 P_{k-1}(a_1, \dots, a_k) + P_{k-2}(a_2, \dots, a_k).$$ We already know that $r_0 = \frac{a_0}{1}$ and $r_1 = \frac{a_0 a_1 + 1}{a_1}$, which means that -$$P_0(a_0)=a_0,\\ P_1(a_0, a_1) = a_0 a_1 + 1$$ +$$\begin{align}P_0(a_0)&=a_0,\\ P_1(a_0, a_1) &= a_0 a_1 + 1.\end{align}$$ For consistency, it is also convenient to define $P_{-1} = 1$ and $P_{-2}=0$, which implies starting points $r_{-1} = \frac{1}{0}$ and $r_{-2}=\frac{0}{1}$. @@ -93,15 +93,15 @@ x_k & 1 & 0 & \dots & 0 \\ 0 & -1 & x_2 & . & \vdots \\ \vdots & \vdots & . & \ddots & 1 \\ 0 & 0 & \dots & -1 & x_0 -\end{bmatrix}$$ +\end{bmatrix}_{\textstyle .}$$ This polynomial is also known as [the continuant](https://en.wikipedia.org/wiki/Continuant_(mathematics)) due to its close relation with continued fraction. Noteworthy, the determinant of such matrix won't change if the sequence on the main diagonal is reversed. This gives us the alternative formula to compute continuants: -$$P_k(a_0, \dots, a_k) = a_k P_{k-1}(a_0, \dots, a_{k-1}) + P_{k-2}(a_0, \dots, a_{k-2})$$ +$$P_k(a_0, \dots, a_k) = a_k P_{k-1}(a_0, \dots, a_{k-1}) + P_{k-2}(a_0, \dots, a_{k-2}).$$ This representation is way more convenient, as it shows that $r_k = \frac{p_k}{q_k}$ can be computed as -$$\frac{p_k}{q_k} = \frac{a_k p_{k-1} + p_{k-2}}{a_k q_{k-1} + q_{k-2}}$$ +$$r_k = \frac{a_k p_{k-1} + p_{k-2}}{a_k q_{k-1} + q_{k-2}}.$$ Thus, $r_k$ is a weighted [mediant](https://en.wikipedia.org/wiki/Mediant_(mathematics)) of $r_{k-1}$ and $r_{k-2}$. From e6c5c73a3258a7ddae7610e56cb3f2b0f32ca840 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Tue, 21 Dec 2021 14:18:33 +0100 Subject: [PATCH 11/45] Update continued-fractions.md expansion --- src/algebra/continued-fractions.md | 65 +++++++++++++++++++++++++----- 1 file changed, 55 insertions(+), 10 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index cb634730b..be5f8d787 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -142,24 +142,24 @@ On the other hand, $a_k$ may be defined as $a_k = \lfloor s_k \rfloor$, thus we ## Convergence -Now that we have some explicit formulas for convergent numbers, let's estimate their distance to the final number $r$. First of all, we can estimate the difference between adjacent convergents: +Let's estimate the distance between $r_k$ and the limit number $r$. The difference between adjacent convergents is given as -$$\frac{p_k}{q_k} - \frac{p_{k-1}}{q_{k-1}} = \frac{p_k q_{k-1} - p_{k-1} q_k}{q_k q_{k-1}}$$ +$$\frac{p_k}{q_k} - \frac{p_{k-1}}{q_{k-1}} = \frac{p_k q_{k-1} - p_{k-1} q_k}{q_k q_{k-1}}.$$ -For the numerator of this fraction, it is possible to get rid of numbers with index $k$: +If $p_k$ and $q_k$ in the numerator are replaced with their corresponding recurrences, we get $$\begin{align} p_k q_{k-1} - p_{k-1} q_k &= (a_k p_{k-1} + p_{k-2}) q_{k-1} - p_{k-1} (a_k q_{k-1} + q_{k-2}) -\\&= p_{k-2} q_{k-1} - p_{k-1} q_{k-2}\end{align}$$ +\\&= p_{k-2} q_{k-1} - p_{k-1} q_{k-2},\end{align}$$ -Thus, the numerator of $r_k - r_{k-1}$ is always the opposite to the numerator of $r_{k-1} - r_{k-2}$. It is equal to $1$ for $a_1 - a_0$, therefore +Which means that the numerator of $r_k - r_{k-1}$ is always the negated numerator of $r_{k-1} - r_{k-2}$. It's equal to $1$ for $a_1 - a_0$, thus -$$r_k - r_{k-1} = \frac{(-1)^{k-1}}{q_k q_{k-1}}$$ +$$r_k - r_{k-1} = \frac{(-1)^{k-1}}{q_k q_{k-1}}.$$ -This allows for alternative representation of $r_k$ as a partial sum of infinite series: +This yields the alternative representation of $r_k$ as a partial sum of infinite series: $$r_k = (r_k - r_{k-1}) + \dots + (r_1 - r_0) + r_0 -= a_0 + \sum\limits_{i=1}^k \frac{(-1)^{i-1}}{q_i q_{i-1}}$$ += a_0 + \sum\limits_{i=1}^k \frac{(-1)^{i-1}}{q_i q_{i-1}}.$$ By definition, $q_k$ monotonically increases at least as fast as Fibonacci numbers, thus @@ -169,7 +169,7 @@ is always well-defined. Noteworthy, the residual series $$r-r_k = \sum\limits_{i=k+1}^\infty \frac{(-1)^{i-1}}{q_i q_{i-1}}$$ -always has the same sign as $(-1)^k$ due to how fast $q_i q_{i-1}$ decreases. It means that even-indexed $r_k$ monotonously approach $r$ from below while odd-indexed $r_k$ monotonously approach it from above: +has the same sign as $(-1)^k$ due to how fast $q_i q_{i-1}$ decreases. It means that even-indexed $r_k$ monotonously approach $r$ from below while odd-indexed $r_k$ monotonously approach it from above:
![Convergence towards underlying number](https://codeforces.com/predownloaded/ca/8d/ca8d8835864ccccea90e458e3d8fa840a6143c13.gif) @@ -177,4 +177,49 @@ always has the same sign as $(-1)^k$ due to how fast $q_i q_{i-1}$ decreases. It From this picture we can see that, in fact, distance between $r$ and $r_k$ is never larger than the distance between $r_k$ and $r_{k+1}$, therefore -$$\left|r-\frac{p_k}{q_k}\right| \leq \frac{1}{q_k q_{k+1}} \leq \frac{1}{q_k^2}$$ +$$\left|r-\frac{p_k}{q_k}\right| \leq \frac{1}{q_k q_{k+1}} \leq \frac{1}{q_k^2}.$$ + +## Geometric interpretation + +If convergents $r_0, r_1, \dots$ are treated as 2-dimensional vectors $\vec r_k=(q_k;p_k)$, the mediant formula above turns into + +$$\vec r_k = a_k \vec r_{k-1} + \vec r_{k-2}.$$ + +To better understand geometric meaning of $\vec r_k$ we need to look closer into computation of $a_k$. Previously we investigated _convergents_ $r_k = [a_0, a_1, \dots, a_k]$. Let's now look on _residuals_ $s_k = [a_{k}, a_{k+1}, \dots]$. From their definition it holds that + +$$s_k = a_{k} + \frac{1}{s_{k+1}}.$$ + +Starting with $s_0=r$, it is possible to derive similar recurrent formulas for $s_k=\frac{b_k}{c_k}$: + +$$\frac{b_k}{c_k}=a_k + \frac{c_{k+1}}{b_{k+1}}.$$ + +Thus, $b_{k+1}=c_k$ and $c_{k+1} = b_k - c_k a_k = c_{k-1} - c_k a_k$. This expression looks very similar to the recurrence for $p_k$ and from the starting points $s_0=\frac{r}{1}$ and $s_1 = \frac{1}{r-a_0}$ we may derive the explicit continuant formula for $c_k$: + +$$c_k = P_{k-1}(r-a_0, -a_1, \dots, -a_{k-1}).$$ + +Taking into consideration the continuant properties (which follow from its determinant definition) + +$$\begin{align} +P_k(a_0, \dots, a_k) &= (-1)^{k+1} P_k(-a_0, \dots, -a_k),\\ +P_k(a_0, \dots, a_k) &= a_0 P_{k-1}(a_1, \dots, a_k) + P_{k-2}(a_2, \dots, a_k), +\end{align}$$ + +we may rearrange the expression for $c_k$ in a much simpler manner: + +$$c_k = (-1)^{k-1} (r q_{k-1} - p_{k-1}).$$ + +This gives us the final formula to calculate residual $s_k$ from convergents: + +$$s_k = \left|\frac{rq_{k-2} - p_{k-2}}{rq_{k-1} - p_{k-1}}\right| = \frac{q_{k-2}}{q_{k-1}}\left|\frac{r - r_{k-2}}{r - r_{k-1}}\right|.$$ + +On the other hand, $a_k$ may be defined as $a_k = \lfloor s_k \rfloor$, thus we have more explicit expression for $a_k$ as well. But what is its geometric meaning in terms of $\vec r_{k-1}$ and $\vec r_{k-2}$? + +### Nose stretching + +From convergence section we know that the number $r$ always lies between numbers $r_{k-1}$ and $r_{k-2}$. For $\vec r_{k-1}$ and $\vec r_{k-2}$ it means that they are always on the opposite sides of the vector $\vec r = (1;r)$. This is due to $r_{k-1}=\frac{p_{k-1}}{q_{k-1}}$ and $r_{k-2}=\frac{p_{k-2}}{q_{k-2}}$ being slope coefficients of $\vec r_{k-1}$ and $\vec r_{k-2}$ correspondingly, while slope coefficient of $\vec r$ is exactly $r$. + +Geometrically, $r q_{k-1} - p_{k-1}$ is equal to $\vec r_{k-1} \times \vec r$, that is, the cross product of $\vec r_{k-1}$ and $\vec r$. Thus, the explicit $\vec r$ formula is + +$$\vec r = \vec r_{k-2} + \left \lfloor \left|\frac{\vec r_{k-2} \times \vec r}{\vec r_{k-1} \times \vec r} \right|\right \rfloor \cdot \vec r_{k-1}.$$ + +Geometrically, $a_k$ here is equal to the maximum integer number of $\vec r_{k-1}$ vectors that can be added to $\vec r_{k-2}$ in such a way that the resulting vector will still be on the same side from $\vec r$ as $\vec r_{k-2}$ is. From 289f8000acc088716255d4d4e80a8a62a2d872fd Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Tue, 21 Dec 2021 14:51:15 +0100 Subject: [PATCH 12/45] Update continued-fractions.md expansion --- src/algebra/continued-fractions.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index be5f8d787..0a1bd9f3f 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -214,6 +214,7 @@ $$s_k = \left|\frac{rq_{k-2} - p_{k-2}}{rq_{k-1} - p_{k-1}}\right| = \frac{q_{k- On the other hand, $a_k$ may be defined as $a_k = \lfloor s_k \rfloor$, thus we have more explicit expression for $a_k$ as well. But what is its geometric meaning in terms of $\vec r_{k-1}$ and $\vec r_{k-2}$? + ### Nose stretching From convergence section we know that the number $r$ always lies between numbers $r_{k-1}$ and $r_{k-2}$. For $\vec r_{k-1}$ and $\vec r_{k-2}$ it means that they are always on the opposite sides of the vector $\vec r = (1;r)$. This is due to $r_{k-1}=\frac{p_{k-1}}{q_{k-1}}$ and $r_{k-2}=\frac{p_{k-2}}{q_{k-2}}$ being slope coefficients of $\vec r_{k-1}$ and $\vec r_{k-2}$ correspondingly, while slope coefficient of $\vec r$ is exactly $r$. @@ -223,3 +224,5 @@ Geometrically, $r q_{k-1} - p_{k-1}$ is equal to $\vec r_{k-1} \times \vec r$, t $$\vec r = \vec r_{k-2} + \left \lfloor \left|\frac{\vec r_{k-2} \times \vec r}{\vec r_{k-1} \times \vec r} \right|\right \rfloor \cdot \vec r_{k-1}.$$ Geometrically, $a_k$ here is equal to the maximum integer number of $\vec r_{k-1}$ vectors that can be added to $\vec r_{k-2}$ in such a way that the resulting vector will still be on the same side from $\vec r$ as $\vec r_{k-2}$ is. + +Noteworthy, $|\vec r_k \times \vec r_{k-1}| = |q_k p_{k-1} - q_{k-1} p_k| = 1$, as was established above. Combined with [Pick's theorem](https://cp-algorithms.com/geometry/picks-theorem.html) it means that there are no points with integer coordinates strictly within the parallelogram formed by $\vec r_{k}$ and $\vec r_{k-1}$. Combined for all possible $k$ it means that there are no integer points in the space between polygons formed by even-indexed and odd-indexed convergent vectors. From c1fb030194ac12a70c9981cd93b977f4dc947990 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Tue, 21 Dec 2021 14:54:38 +0100 Subject: [PATCH 13/45] Update continued-fractions.md duplicate geometry part --- src/algebra/continued-fractions.md | 35 ------------------------------ 1 file changed, 35 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 0a1bd9f3f..24667eee9 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -105,41 +105,6 @@ $$r_k = \frac{a_k p_{k-1} + p_{k-2}}{a_k q_{k-1} + q_{k-2}}.$$ Thus, $r_k$ is a weighted [mediant](https://en.wikipedia.org/wiki/Mediant_(mathematics)) of $r_{k-1}$ and $r_{k-2}$. -## Geometric interpretation - -If convergents $r_0, r_1, \dots$ are treated as 2-dimensional vectors $\vec r_k=(p_k;q_k)$, the mediant formula above turns into - -$$\vec r_k = a_k \vec r_{k-1} + \vec r_{k-2}.$$ - -To better understand geometric meaning of $\vec r_k$ we need to look closer into computation of $a_k$. Previously we investigated _convergents_ $r_k = [a_0, a_1, \dots, a_k]$. Let's now look on _residuals_ $s_k = [a_{k}, a_{k+1}, \dots]$. From their definition it holds that - -$$\left.s_k = a_{k} + \frac{1}{s_{k+1}}\right._{\textstyle .}$$ - -Starting with $s_0=r$, it is possible to derive similar recurrent formulas for $s_k=\frac{b_k}{c_k}$: - -$$\left.\frac{b_k}{c_k}=a_k + \frac{c_{k+1}}{b_{k+1}}\right._{\textstyle .}$$ - -Thus, $b_{k+1}=c_k$ and $c_{k+1} = b_k - c_k a_k = c_{k-1} - c_k a_k$. This expression looks very close to the continuant and from the starting points $s_0=\frac{r}{1}$ and $s_1 = \frac{1}{r-a_0}$ one may derive the explicit formula for $c_k$: - -$$c_k = P_{k-1}(r-a_0, -a_1, \dots, -a_{k-1}).$$ - -Taking into consideration the continuant properties (which follow from its determinant representation) - -$$\begin{align} -P_k(a_0, \dots, a_k) &= (-1)^{k+1} P_k(-a_0, \dots, -a_k),\\ -P_k(a_0, \dots, a_k) &= a_0 P_{k-1}(a_1, \dots, a_k) + P_{k-2}(a_2, \dots, a_k), -\end{align}$$ - -we may rearrange the expression for $c_k$ in a much simpler manner: - -$$c_k = (-1)^{k-1} (r q_{k-1} - p_{k-1}).$$ - -This gives us the final formula to calculate residual $s_k$ from convergents: - -$$s_k = \left|\frac{rq_{k-2} - p_{k-2}}{rq_{k-1} - p_{k-1}}\right|_{\textstyle .}$$ - -On the other hand, $a_k$ may be defined as $a_k = \lfloor s_k \rfloor$, thus we have more explicit expression for $a_k$ as well. - ## Convergence Let's estimate the distance between $r_k$ and the limit number $r$. The difference between adjacent convergents is given as From 4f2773f396c0fb7e91e69e6f76eaa661bc770ca9 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Sun, 9 Jan 2022 19:57:26 +0100 Subject: [PATCH 14/45] Update continued-fractions.md minor edits + impl for convergents --- src/algebra/continued-fractions.md | 34 ++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 24667eee9..1d17148a2 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -1,21 +1,21 @@ # Continued fractions in competitive programming -**Continued fraction** is a way of representing arbitrary real number as a convergent sequence of rational numbers. What makes them important and useful in competitive programming is the fact that each consequent fraction is, in a way, the best possible approximation of the specified real number. Besides that, continued fractions are closely related to Euclidean algorithm which makes them useful in a bunch of number-theoretical problems. +**Continued fraction** is a way of representing arbitrary real number as a convergent sequence of rational numbers. They are useful in competitive programming because they can are easy to compute and each consequent fraction is, in a way, the best possible approximation of the underlying real number. Besides that, continued fractions are closely related to Euclidean algorithm which makes them useful in a bunch of number-theoretical problems. ## Definitions ### Continued fraction representation -Any real number $r$ may be uniquely represented as $r = a_0 + \frac{1}{q_0}$ where $a_0 = \lfloor r \rfloor$ and $q_0$ is either infinite (meaning $r$ is an integer) or is a real number greater than $1$. Expanding it indefinitely, one obtains the so-called continued fraction representation +Any real number $r$ may be uniquely represented as $r = a_0 + \frac{1}{q_0}$ where $a_0 = \lfloor r \rfloor$ and $q_0$ is either infinite (meaning that $r$ is an integer) or is a real number greater than $1$. Expanding it indefinitely, one obtains the so-called continued fraction representation $$r=a_0 + \frac{1}{a_1 + \frac{1}{a_2+\dots}},$$ -which is shortly denoted as $r=[a_0, a_1, \dots]$.For consistency, the representation of the infinity is defined here as $\infty = [\infty, \infty, \dots]$. Therefore, rational numbers can be distinguished from irrational by the fact that their continued fraction representation always ends with a sequence of infinities. For example, +which is shortly denoted as $r=[a_0, a_1, \dots]$. For consistency, we define the representation of the infinity as $\infty = [\infty, \infty, \dots]$. Therefore, rational numbers can be distinguished from irrational by the fact that their continued fraction representation always ends with a sequence of infinities. For example, $$\frac{5}{3} = 1 + \frac{1}{1+\frac{1}{2+\frac{1}{\infty}}} = [1,1,2,\infty,\infty,\dots].$$ -We will drop the infinite part of the expansion of rational numbers for shortness, thus $\frac{5}{3}=[1,1,2]$. +We will drop the infinite part of the expansion of rational numbers for shortness, thus writing $\frac{5}{3}=[1,1,2]$. Note that $[1,1,1,1]$, if treated as continued fraction, would also represent $\frac 5 3$. Generally, there is a unique way to represent any irrational number and there are exactly two ways to represent any rational number, which are $[a_0, \dots, a_k]$ and $[a_0, \dots, a_k-1, 1]$. We will stick to the first one, as it is consistent with the way continued fractions were defined for irrational numbers through flooring. @@ -53,9 +53,13 @@ struct fraction { Now that both finite and infinite continued fraction representations are defined, let's define convergent sequence which corresponds the underlying real number. For the number $r=[a_0, a_1, a_2, \dots]$, its convergent sequence is defined as -$$r_0=[a_0],\\r_1=[a_0, a_1],\\ \dots,\\ r_k=[a_0, a_1, \dots, a_k].$$ +\begin{gather} +r_0=[a_0],\\r_1=[a_0, a_1],\\ \dots,\\ r_k=[a_0, a_1, \dots, a_k]. +\end{gather} -Each individual rational number $r_k$ is called the convergent of $r$. It is important to understand how these rational numbers are constructed and how they relate with the underlying number $r$. The numerator and denominator of $r_k$ are polynomials of $a_0, a_1, \dots, a_k$. These polynomials only depend on the number of variables $k$, that is +Each individual rational number $r_k$ is called the convergent of $r$. It is important to understand how these rational numbers are constructed and how they relate with the underlying number $r$. Doing this will shed some light on why they're called the best rational approximations of $r$ and also give us an efficient algorithm to compute them. + +The numerator and denominator of $r_k$ are multivariate polynomials of $a_0, a_1, \dots, a_k$. These polynomials only depend on the number of variables $k$, thus it holds that $$r_k = \frac{P_k(a_0, a_1, \dots, a_k)}{Q_k(a_0,a_1, \dots, a_k)}.$$ @@ -105,6 +109,24 @@ $$r_k = \frac{a_k p_{k-1} + p_{k-2}}{a_k q_{k-1} + q_{k-2}}.$$ Thus, $r_k$ is a weighted [mediant](https://en.wikipedia.org/wiki/Mediant_(mathematics)) of $r_{k-1}$ and $r_{k-2}$. +#### Implementation + +For the reasons that will be evident as we move further to the geometric interpretation of continued fractions, we will use a [point-like data structure](geometry/basic-geometry.html) to represent $r_k = \frac{p_k}{q_k}$ as a point $(q_k, p_k)$ on the Euclidean plane. + +```cpp +struct fraction { + ... + + vector convergents() { + vector r = {{1, 0}, {0, 1}}; + for(size_t i = 0; i < a.size(); i++) { + r.push_back(r[i + 1] * a[i] + r[i]); + } + return r; + } +}; +``` + ## Convergence Let's estimate the distance between $r_k$ and the limit number $r$. The difference between adjacent convergents is given as From cbe3eef10e483f02f700a4a37cbde82d3bb49114 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Mon, 10 Jan 2022 00:05:01 +0100 Subject: [PATCH 15/45] Update continued-fractions.md better illustration --- src/algebra/continued-fractions.md | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 1d17148a2..766be0928 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -127,39 +127,44 @@ struct fraction { }; ``` + ## Convergence -Let's estimate the distance between $r_k$ and the limit number $r$. The difference between adjacent convergents is given as +Let's estimate the distance between $r_k$ and the underlying number $r$. To do this, we start by estimating the difference between adjacent convergents. By definition, it is given by the following formula $$\frac{p_k}{q_k} - \frac{p_{k-1}}{q_{k-1}} = \frac{p_k q_{k-1} - p_{k-1} q_k}{q_k q_{k-1}}.$$ -If $p_k$ and $q_k$ in the numerator are replaced with their corresponding recurrences, we get +Replacing $p_k$ and $q_k$ in the numerator with their recurrences, we get $$\begin{align} p_k q_{k-1} - p_{k-1} q_k &= (a_k p_{k-1} + p_{k-2}) q_{k-1} - p_{k-1} (a_k q_{k-1} + q_{k-2}) \\&= p_{k-2} q_{k-1} - p_{k-1} q_{k-2},\end{align}$$ -Which means that the numerator of $r_k - r_{k-1}$ is always the negated numerator of $r_{k-1} - r_{k-2}$. It's equal to $1$ for $a_1 - a_0$, thus +thus the numerator of $r_k - r_{k-1}$ is always the negated numerator of $r_{k-1} - r_{k-2}$. It, in turn, equals to $1$ for + +$$r_1 - r_0=\left(a_0+\frac{1}{a_1}\right)-a_0=\frac{1}{a_1},$$ + +thus $$r_k - r_{k-1} = \frac{(-1)^{k-1}}{q_k q_{k-1}}.$$ -This yields the alternative representation of $r_k$ as a partial sum of infinite series: +This yields an alternative representation of $r_k$ as a partial sum of infinite series: $$r_k = (r_k - r_{k-1}) + \dots + (r_1 - r_0) + r_0 = a_0 + \sum\limits_{i=1}^k \frac{(-1)^{i-1}}{q_i q_{i-1}}.$$ -By definition, $q_k$ monotonically increases at least as fast as Fibonacci numbers, thus +From the recurrence relation it follows that $q_k$ monotonously increases at least as fast as Fibonacci numbers, thus $$r = \lim\limits_{k \to \infty} r_k = a_0 + \sum\limits_{i=1}^\infty \frac{(-1)^{i-1}}{q_i q_{i-1}}$$ -is always well-defined. Noteworthy, the residual series +is always well-defined, as the underlying series always converge. Noteworthy, the residual series $$r-r_k = \sum\limits_{i=k+1}^\infty \frac{(-1)^{i-1}}{q_i q_{i-1}}$$ has the same sign as $(-1)^k$ due to how fast $q_i q_{i-1}$ decreases. It means that even-indexed $r_k$ monotonously approach $r$ from below while odd-indexed $r_k$ monotonously approach it from above:
-![Convergence towards underlying number](https://codeforces.com/predownloaded/ca/8d/ca8d8835864ccccea90e458e3d8fa840a6143c13.gif) +![Convergence towards underlying number](https://upload.wikimedia.org/wikipedia/commons/b/b4/Golden_ration_convergents.svg)
From this picture we can see that, in fact, distance between $r$ and $r_k$ is never larger than the distance between $r_k$ and $r_{k+1}$, therefore From 8fce993f15796a34f797480387e6f029fc84591e Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Mon, 10 Jan 2022 10:40:06 +0100 Subject: [PATCH 16/45] Update continued-fractions.md style --- src/algebra/continued-fractions.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 766be0928..c1423b65a 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -128,9 +128,10 @@ struct fraction { ``` + ## Convergence -Let's estimate the distance between $r_k$ and the underlying number $r$. To do this, we start by estimating the difference between adjacent convergents. By definition, it is given by the following formula +Let's estimate the distance between $r_k$ and the underlying number $r$. To do this, we start by estimating the difference between adjacent convergents. By definition, it is given with the following formula $$\frac{p_k}{q_k} - \frac{p_{k-1}}{q_{k-1}} = \frac{p_k q_{k-1} - p_{k-1} q_k}{q_k q_{k-1}}.$$ @@ -167,7 +168,11 @@ has the same sign as $(-1)^k$ due to how fast $q_i q_{i-1}$ decreases. It means ![Convergence towards underlying number](https://upload.wikimedia.org/wikipedia/commons/b/b4/Golden_ration_convergents.svg)
-From this picture we can see that, in fact, distance between $r$ and $r_k$ is never larger than the distance between $r_k$ and $r_{k+1}$, therefore +From this picture we can see that + +$$|r-r_k| = |r_k - r_{k+1}| - |r-r_{k+1}| \leq |r_k - r_{k+1}|,$$ + +thus the distance between $r$ and $r_k$ is never larger than the distance between $r_k$ and $r_{k+1}$: $$\left|r-\frac{p_k}{q_k}\right| \leq \frac{1}{q_k q_{k+1}} \leq \frac{1}{q_k^2}.$$ From bf410b4553be622d8dbf3469c2ba94f08b48e773 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Mon, 10 Jan 2022 16:59:18 +0100 Subject: [PATCH 17/45] Update continued-fractions.md expansion --- src/algebra/continued-fractions.md | 49 ++++++++++++++++-------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index c1423b65a..311fc8feb 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -176,50 +176,53 @@ thus the distance between $r$ and $r_k$ is never larger than the distance betwee $$\left|r-\frac{p_k}{q_k}\right| \leq \frac{1}{q_k q_{k+1}} \leq \frac{1}{q_k^2}.$$ + ## Geometric interpretation -If convergents $r_0, r_1, \dots$ are treated as 2-dimensional vectors $\vec r_k=(q_k;p_k)$, the mediant formula above turns into +If convergents $r_0, r_1, \dots$ are treated as 2-dimensional vectors $\vec r_k=(q_k,p_k)$, the mediant formula above turns into $$\vec r_k = a_k \vec r_{k-1} + \vec r_{k-2}.$$ -To better understand geometric meaning of $\vec r_k$ we need to look closer into computation of $a_k$. Previously we investigated _convergents_ $r_k = [a_0, a_1, \dots, a_k]$. Let's now look on _residuals_ $s_k = [a_{k}, a_{k+1}, \dots]$. From their definition it holds that +To better understand the geometric meaning of $\vec r_k$ we need to look closer into the computation of $a_k$. -$$s_k = a_{k} + \frac{1}{s_{k+1}}.$$ +### Residuals -Starting with $s_0=r$, it is possible to derive similar recurrent formulas for $s_k=\frac{b_k}{c_k}$: +Previously we investigated the _convergents_ $r_k = [a_0, a_1, \dots, a_k]$. Let's now look on the _residuals_ $s_k = [a_{k}, a_{k+1}, \dots]$. From their definition it holds that -$$\frac{b_k}{c_k}=a_k + \frac{c_{k+1}}{b_{k+1}}.$$ +$$s_k = a_{k} + \frac{1}{s_{k+1}},$$ -Thus, $b_{k+1}=c_k$ and $c_{k+1} = b_k - c_k a_k = c_{k-1} - c_k a_k$. This expression looks very similar to the recurrence for $p_k$ and from the starting points $s_0=\frac{r}{1}$ and $s_1 = \frac{1}{r-a_0}$ we may derive the explicit continuant formula for $c_k$: +which implies $a_k = \lfloor s_k \rfloor$, so we will get an explicit way to determine $a_k$ if we know how to compute $s_k$. On the other hand, if we formally substitute $a_k$ with $s_k$, that is look on the expression $[a_0, a_1, \dots, a_{k-1}, s_k]$, it will be equal to $r$, thus -$$c_k = P_{k-1}(r-a_0, -a_1, \dots, -a_{k-1}).$$ +$$\vec r = s_k \vec r_{k-1} + \vec r_{k-2},$$ -Taking into consideration the continuant properties (which follow from its determinant definition) +where $\vec r = (1, r)$. Taking cross product of both parts with $\vec r$, we obtain the explicit formula for $s_k$: -$$\begin{align} -P_k(a_0, \dots, a_k) &= (-1)^{k+1} P_k(-a_0, \dots, -a_k),\\ -P_k(a_0, \dots, a_k) &= a_0 P_{k-1}(a_1, \dots, a_k) + P_{k-2}(a_2, \dots, a_k), -\end{align}$$ +$$s_k = -\frac{\vec r \times \vec r_{k-2}}{\vec r \times \vec r_{k-1}}=\left|\frac{\vec r \times \vec r_{k-2}}{\vec r \times \vec r_{k-1}}\right|=\left|\frac{r q_{k-2} - p_{k-2}}{rq_{k-1}-p_{k-1}}\right|=\frac{q_{k-2}}{q_{k-1}}\left|\frac{r -r_{k-2}}{r-r_{k-1}}\right|.$$ -we may rearrange the expression for $c_k$ in a much simpler manner: +Thus, the expression for $\vec r_k$ is given explicitly as -$$c_k = (-1)^{k-1} (r q_{k-1} - p_{k-1}).$$ +$$\vec r_k = \vec r_{k-2} + \left\lfloor \left| \frac{\vec r \times \vec r_{k-2}}{\vec r \times \vec r_{k-1}}\right|\right\rfloor \cdot \vec r_{k-1}.$$ -This gives us the final formula to calculate residual $s_k$ from convergents: +Note that $\vec r \times \vec r_{k-2}$ and $\vec r \times \vec r_{k-1}$ never have the same sign, as $\vec r_{k-1}$ and $\vec r_{k-2}$ always lie on different size of $\vec r$ due to the fact that their slope coefficients are $r_{k-1}$ and $r_{k-2}$, while the slope coefficient of $\vec r$ is $r$. -$$s_k = \left|\frac{rq_{k-2} - p_{k-2}}{rq_{k-1} - p_{k-1}}\right| = \frac{q_{k-2}}{q_{k-1}}\left|\frac{r - r_{k-2}}{r - r_{k-1}}\right|.$$ +### Nose stretching -On the other hand, $a_k$ may be defined as $a_k = \lfloor s_k \rfloor$, thus we have more explicit expression for $a_k$ as well. But what is its geometric meaning in terms of $\vec r_{k-1}$ and $\vec r_{k-2}$? +Geometrically, $a_k$ in the expression above is equal to the maximum integer number of $\vec r_{k-1}$ vectors that can be added to $\vec r_{k-2}$ in such a way that the resulting vector will still be on the same side from $\vec r$ as $\vec r_{k-2}$ is. +![](https://upload.wikimedia.org/wikipedia/commons/9/92/Continued_convergents_geometry.svg) -### Nose stretching +On the picture above you can see how $\vec r_2 = (4,3)$ is obtained by repeatedly adding $\vec r_1 = (1,1)$ to $\vec r_0 = (1, 0)$. When it is not possible to further add $\vec r_1$ to $\vec r_0$ without crossing the $y=rx$ line, we go to the other side and repeatedly add $\vec r_2$ to $\vec r_1$ to obtain $\vec r_3 = (9, 7)$ in a similar manner. + +This procedure generates exponentially longer vectors, that approach closer and closer to $y=rx$ line, until one vector is finally collinear with it (when $r$ is rational). For this property, the procedure of generating consequent convergent vectors was dubbed nose stretching algorithm by Boris Delaunay. + +### Klein polygons -From convergence section we know that the number $r$ always lies between numbers $r_{k-1}$ and $r_{k-2}$. For $\vec r_{k-1}$ and $\vec r_{k-2}$ it means that they are always on the opposite sides of the vector $\vec r = (1;r)$. This is due to $r_{k-1}=\frac{p_{k-1}}{q_{k-1}}$ and $r_{k-2}=\frac{p_{k-2}}{q_{k-2}}$ being slope coefficients of $\vec r_{k-1}$ and $\vec r_{k-2}$ correspondingly, while slope coefficient of $\vec r$ is exactly $r$. +If we look on the triangle drawn on points $\vec r_{k-2}$, $\vec r_{k}$ and $\vec 0$ we will notice that its doubled area is -Geometrically, $r q_{k-1} - p_{k-1}$ is equal to $\vec r_{k-1} \times \vec r$, that is, the cross product of $\vec r_{k-1}$ and $\vec r$. Thus, the explicit $\vec r$ formula is +$$|\vec r_{k-2} \times \vec r_k| = a_k.$$ -$$\vec r = \vec r_{k-2} + \left \lfloor \left|\frac{\vec r_{k-2} \times \vec r}{\vec r_{k-1} \times \vec r} \right|\right \rfloor \cdot \vec r_{k-1}.$$ +Combined with the [Pick's theorem](https://cp-algorithms.com/geometry/picks-theorem.html), it means that there are no lattice points strictly inside the triangle and the only lattice points on its border are $\vec 0$ and $\vec r_{k-2} + t \cdot \vec r_{k-1}$ for all integer $t$ such that $0 \leq t \leq a_k$. When joined for all possible $k$ it means that there are no integer points in the space between polygons formed by even-indexed and odd-indexed convergent vectors. -Geometrically, $a_k$ here is equal to the maximum integer number of $\vec r_{k-1}$ vectors that can be added to $\vec r_{k-2}$ in such a way that the resulting vector will still be on the same side from $\vec r$ as $\vec r_{k-2}$ is. +This, in turn, means that $\vec r_k$ with odd coefficients form a convex hull of lattice points with $x \geq 0$ above the line $y=rx$, while $\vec r_k$ with even coefficients form a convex hull of lattice points with $x > 0$ below the line $y=rx$. -Noteworthy, $|\vec r_k \times \vec r_{k-1}| = |q_k p_{k-1} - q_{k-1} p_k| = 1$, as was established above. Combined with [Pick's theorem](https://cp-algorithms.com/geometry/picks-theorem.html) it means that there are no points with integer coordinates strictly within the parallelogram formed by $\vec r_{k}$ and $\vec r_{k-1}$. Combined for all possible $k$ it means that there are no integer points in the space between polygons formed by even-indexed and odd-indexed convergent vectors. +These polygons are also known as Klein polygons, named after Felix Klein who first suggested this geometric interpretation to the continued fractions. From 8ca4c13c2208f950b2bd041f0af8b74486ebe1a4 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Mon, 10 Jan 2022 17:00:13 +0100 Subject: [PATCH 18/45] Update continued-fractions.md no need for this --- src/algebra/continued-fractions.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 311fc8feb..6ddac3b3d 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -164,9 +164,7 @@ $$r-r_k = \sum\limits_{i=k+1}^\infty \frac{(-1)^{i-1}}{q_i q_{i-1}}$$ has the same sign as $(-1)^k$ due to how fast $q_i q_{i-1}$ decreases. It means that even-indexed $r_k$ monotonously approach $r$ from below while odd-indexed $r_k$ monotonously approach it from above: -
-![Convergence towards underlying number](https://upload.wikimedia.org/wikipedia/commons/b/b4/Golden_ration_convergents.svg) -
+![](https://upload.wikimedia.org/wikipedia/commons/b/b4/Golden_ration_convergents.svg) From this picture we can see that From 4c66c36d91843d06623f23fdf7cb424cc3d332b0 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Mon, 24 Jan 2022 21:31:51 +0100 Subject: [PATCH 19/45] rewriting definitions section --- src/algebra/continued-fractions.md | 73 +++++++++++++++++++++++++++--- 1 file changed, 66 insertions(+), 7 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 6ddac3b3d..d1afcfe6d 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -1,23 +1,82 @@ # Continued fractions in competitive programming -**Continued fraction** is a way of representing arbitrary real number as a convergent sequence of rational numbers. They are useful in competitive programming because they can are easy to compute and each consequent fraction is, in a way, the best possible approximation of the underlying real number. Besides that, continued fractions are closely related to Euclidean algorithm which makes them useful in a bunch of number-theoretical problems. +**Continued fraction** is a representation of a real number as a specific convergent sequence of rational numbers. They are useful in competitive programming because they are easy to compute and can be efficiently used to find the best possible approximation of the underlying real number with a rational number (among all numbers whose denominator doesn't exceed a given value). + +Besides that, continued fractions are closely related to Euclidean algorithm which makes them useful in a bunch of number-theoretical problems. ## Definitions ### Continued fraction representation -Any real number $r$ may be uniquely represented as $r = a_0 + \frac{1}{q_0}$ where $a_0 = \lfloor r \rfloor$ and $q_0$ is either infinite (meaning that $r$ is an integer) or is a real number greater than $1$. Expanding it indefinitely, one obtains the so-called continued fraction representation +!!! abstract "Definition" + + Let $a_0, a_1, \dots, a_k \in \mathbb Z$ and $a_1, a_2, \dots, a_k \geq 1$. Then the expression + + $$r=a_0 + \frac{1}{a_1 + \frac{1}{\dots + \frac{1}{a_k}}},$$ + + is called the **continued fraction representation** of the rational number $r$ and is denoted shortly as $r=[a_0;a_1,a_2,\dots,a_k]$. + +??? example + + Let $r = \frac{5}{3}$. There are two ways to represent it as a continued fraction: + + $$ + \begin{align} + r = [1;1,1,1] &= 1+\frac{1}{1+\frac{1}{1+\frac{1}{1}}},\\ + r = [1;1,2] &= 1+\frac{1}{1+\frac{1}{2}}. + \end{align} + $$ + +It can be proven that any rational number can be represented as a continued fraction in exactly $2$ ways: + +$$r = [a_0;a_1,\dots,a_k,1] = [a_0;a_1,\dots,a_k+1].$$ + +Moreover, the length $k$ of continued fraction is bounded as $k = O(\log \min(p, q))$. + +The reasoning behind this will be clear once we delve into details of the continued fraction construction. + +!!! abstract "Definition" + + Let $a_0,a_1,a_2, \dots$ be an integer sequence such that $a_1, a_2, \dots \geq 1$. Let $r_k = [a_0; a_1, \dots, a_k]$. Then the expression + + $$r = a_0 + \frac{1}{a_1 + \frac{1}{a_2+\dots}} = \lim\limits_{k \to \infty} r_k.$$ + + is called the **continued fraction representation** of the irrational number $r$ and is denoted shortly as $r = [a_0;a_1,a_2,\dots]$. + +!!! abstract "Definition" + + In the definition above, rational numbers $r_0, r_1, r_2, \dots$ are called the **convergents** of $r$. + + Correspondingly, individual $r_k = [a_0; a_1, \dots, a_k]$ is called the $k$-th **convergent** of $r$. + +??? example + + Consider $r = [1; 1, 1, 1, \dots]$. It can be proven by induction that $r_k = \frac{F_{k+2}}{F_{k+1}}$, where $F_k$ is the Fibonacci sequence defined as $F_0 = 0$, $F_1 = 1$ and $F_{k} = F_{k-1} + F_{k-2}$. From the Binet's formula, it is known that + + $$r_k = \frac{\phi^{k+2} - \psi^{k+2}}{\phi^{k+1} - \psi^{k+1}},$$ + + where $\phi = \frac{1+\sqrt{5}}{2} \approx 1.618$ is the golden ratio and $\psi = \frac{1-\sqrt{5}}{2} = -\frac{1}{\phi} \approx -0.618$. Thus, + + $$r = 1+\frac{1}{1+\frac{1}{1+\dots}}=\lim\limits_{k \to \infty} r_k = \phi = \frac{1+\sqrt{5}}{2}.$$ + + Note that in this specific case, an alternative way to find $r$ would be to solve the equation + + $$r = 1+\frac{1}{r} \implies r^2 = r + 1. $$ + +!!! abstract "Definition" + + Complementary to convergents, we define the **residues** as $s_k = [a_k; a_{k+1}, a_{k+2}, \dots]$. Correspondingly, we will call an individual $s_k$ the $k$-th residual of $r$. -$$r=a_0 + \frac{1}{a_1 + \frac{1}{a_2+\dots}},$$ +From the definitions above, one may conclude that $s_k \geq 1$ for $k \geq 1$. If we allow the last term in $[a_0; a_1, \dots, a_k]$ to be an arbitrary real number $s$ and treat it formally as an algebraic expression, the following equation will hold for any $k$: -which is shortly denoted as $r=[a_0, a_1, \dots]$. For consistency, we define the representation of the infinity as $\infty = [\infty, \infty, \dots]$. Therefore, rational numbers can be distinguished from irrational by the fact that their continued fraction representation always ends with a sequence of infinities. For example, +$$r = [a_0; a_1, \dots, a_{k-1}, s_k],$$ -$$\frac{5}{3} = 1 + \frac{1}{1+\frac{1}{2+\frac{1}{\infty}}} = [1,1,2,\infty,\infty,\dots].$$ +in particular $r = [s_0] = s_0$. This, in turn, allows us to deduct that -We will drop the infinite part of the expansion of rational numbers for shortness, thus writing $\frac{5}{3}=[1,1,2]$. +$$s_k = [a_k; s_{k+1}] = a_k + \frac{1}{s_{k+1}} \implies a_k = \lfloor s_k \rfloor,$$ -Note that $[1,1,1,1]$, if treated as continued fraction, would also represent $\frac 5 3$. Generally, there is a unique way to represent any irrational number and there are exactly two ways to represent any rational number, which are $[a_0, \dots, a_k]$ and $[a_0, \dots, a_k-1, 1]$. We will stick to the first one, as it is consistent with the way continued fractions were defined for irrational numbers through flooring. +thus the sequence $a_0, a_1, \dots$ is uniquely defined for any irrational number $r$. #### Implementation From 57a23602677165e8713a591fa471b8f247d4767d Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Tue, 25 Jan 2022 19:57:03 +0100 Subject: [PATCH 20/45] fix link --- src/algebra/continued-fractions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index d1afcfe6d..9a420b162 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -170,7 +170,7 @@ Thus, $r_k$ is a weighted [mediant](https://en.wikipedia.org/wiki/Mediant_(mathe #### Implementation -For the reasons that will be evident as we move further to the geometric interpretation of continued fractions, we will use a [point-like data structure](geometry/basic-geometry.html) to represent $r_k = \frac{p_k}{q_k}$ as a point $(q_k, p_k)$ on the Euclidean plane. +For the reasons that will be evident as we move further to the geometric interpretation of continued fractions, we will use a [point-like data structure](../geometry/basic-geometry.html) to represent $r_k = \frac{p_k}{q_k}$ as a point $(q_k, p_k)$ on the Euclidean plane. ```cpp struct fraction { From 8c24faefbbe86059fb82b62e06bc6cb58ff0c790 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Sat, 12 Feb 2022 20:48:18 +0100 Subject: [PATCH 21/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 39 ++++++++++++++++-------------- 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 9a420b162..60dfab675 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -34,7 +34,7 @@ $$r = [a_0;a_1,\dots,a_k,1] = [a_0;a_1,\dots,a_k+1].$$ Moreover, the length $k$ of continued fraction is bounded as $k = O(\log \min(p, q))$. -The reasoning behind this will be clear once we delve into details of the continued fraction construction. +The reasoning behind this will be clear once we delve into the details of the continued fraction construction. !!! abstract "Definition" @@ -80,33 +80,36 @@ thus the sequence $a_0, a_1, \dots$ is uniquely defined for any irrational numbe #### Implementation -In the code snippets we will mostly assume that we work with the finite continued fractions. Although continued fractions defined recursively it is more efficient to construct them iteratively. If we start with $r=\frac{p}{q}$, the transition looks like +In the code snippets we will mostly assume that we work with the finite continued fractions. Although continued fractions defined recursively it is more efficient to construct them iteratively. If we start with $s_k=\frac{p}{q}$, the transition looks like -$$r =\left\lfloor \frac p q \right\rfloor + \frac{1}{\left(\frac{p}{q}-\left\lfloor \frac{p}{q}\right\rfloor\right)^{-1}}.$$ +$$s_k =\left\lfloor \frac p q \right\rfloor + \frac{1}{s_{k+1}}.$$ -The denominator part of this expression may be rewritten as +From this expression, the next residue $s_{k+1}$ is obtained as -$$\left(\frac{p}{q}-\left\lfloor \frac{p}{q}\right\rfloor\right)^{-1} = \frac{q}{p-q\cdot \lfloor \frac{p}{q} \rfloor} = \frac{q}{p \bmod q}.$$ +$$s_{k+1} = \left(\frac{p}{q}-\left\lfloor \frac{p}{q}\right\rfloor\right)^{-1} = \frac{q}{p-q\cdot \lfloor \frac{p}{q} \rfloor} = \frac{q}{p \bmod q}.$$ Thus, computation of a continued fraction representation for $r=\frac{p}{q}$ follows the same steps as the Euclidean algorithm for $p$ and $q$. - -```cpp -struct fraction { - vector a; - - fraction():a{0}{} - - // Assuming 0 <= p and 0 < q - fraction(int p, int q) { +=== "C++" + ```cpp + auto fraction(int p, int q) { + vector a; while(q) { a.push_back(p / q); - p %= q; - swap(p, q); + tie(p, q) = make_pair(q, p % q); } + return a; } -}; -``` + ``` +=== "Python" + ```py + def fraction(p, q): + a = [] + while q: + a.append(p // q) + p, q = q, p % q + return a + ``` ### Convergents From 4612ce3cbaf37de63a244a2c762eeed81a071c27 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Sat, 12 Feb 2022 20:49:10 +0100 Subject: [PATCH 22/45] html -> md --- src/algebra/continued-fractions.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 60dfab675..03d9bd3ca 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -173,7 +173,7 @@ Thus, $r_k$ is a weighted [mediant](https://en.wikipedia.org/wiki/Mediant_(mathe #### Implementation -For the reasons that will be evident as we move further to the geometric interpretation of continued fractions, we will use a [point-like data structure](../geometry/basic-geometry.html) to represent $r_k = \frac{p_k}{q_k}$ as a point $(q_k, p_k)$ on the Euclidean plane. +For the reasons that will be evident as we move further to the geometric interpretation of continued fractions, we will use a [point-like data structure](../geometry/basic-geometry.md) to represent $r_k = \frac{p_k}{q_k}$ as a point $(q_k, p_k)$ on the Euclidean plane. ```cpp struct fraction { @@ -281,7 +281,7 @@ If we look on the triangle drawn on points $\vec r_{k-2}$, $\vec r_{k}$ and $\ve $$|\vec r_{k-2} \times \vec r_k| = a_k.$$ -Combined with the [Pick's theorem](https://cp-algorithms.com/geometry/picks-theorem.html), it means that there are no lattice points strictly inside the triangle and the only lattice points on its border are $\vec 0$ and $\vec r_{k-2} + t \cdot \vec r_{k-1}$ for all integer $t$ such that $0 \leq t \leq a_k$. When joined for all possible $k$ it means that there are no integer points in the space between polygons formed by even-indexed and odd-indexed convergent vectors. +Combined with the [Pick's theorem](../geometry/picks-theorem.md), it means that there are no lattice points strictly inside the triangle and the only lattice points on its border are $\vec 0$ and $\vec r_{k-2} + t \cdot \vec r_{k-1}$ for all integer $t$ such that $0 \leq t \leq a_k$. When joined for all possible $k$ it means that there are no integer points in the space between polygons formed by even-indexed and odd-indexed convergent vectors. This, in turn, means that $\vec r_k$ with odd coefficients form a convex hull of lattice points with $x \geq 0$ above the line $y=rx$, while $\vec r_k$ with even coefficients form a convex hull of lattice points with $x > 0$ below the line $y=rx$. From 8a8d5401d5069479a2e9797fc87dbd149caf4777 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Sat, 12 Feb 2022 21:34:49 +0100 Subject: [PATCH 23/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 59 +++++++++++++++++------------- 1 file changed, 34 insertions(+), 25 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 03d9bd3ca..33bd12cf8 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -113,21 +113,23 @@ Thus, computation of a continued fraction representation for $r=\frac{p}{q}$ fol ### Convergents -Now that both finite and infinite continued fraction representations are defined, let's define convergent sequence which corresponds the underlying real number. For the number $r=[a_0, a_1, a_2, \dots]$, its convergent sequence is defined as +Let's take a closer look at the convergents that were defined earlier. For $r=[a_0, a_1, a_2, \dots]$, its convergents are \begin{gather} r_0=[a_0],\\r_1=[a_0, a_1],\\ \dots,\\ r_k=[a_0, a_1, \dots, a_k]. \end{gather} -Each individual rational number $r_k$ is called the convergent of $r$. It is important to understand how these rational numbers are constructed and how they relate with the underlying number $r$. Doing this will shed some light on why they're called the best rational approximations of $r$ and also give us an efficient algorithm to compute them. +It is important to understand how these rational numbers are constructed and how they relate with the underlying number $r$, as they're the main building blocks of everything else related to the continued fraction. -The numerator and denominator of $r_k$ are multivariate polynomials of $a_0, a_1, \dots, a_k$. These polynomials only depend on the number of variables $k$, thus it holds that +#### Recurrent relations + +The numerator and the denominator of $r_k$ are multivariate polynomials of $a_0, a_1, \dots, a_k$. These polynomials only depend on the number of variables $k$, thus it holds that $$r_k = \frac{P_k(a_0, a_1, \dots, a_k)}{Q_k(a_0,a_1, \dots, a_k)}.$$ On the other hand, -$$r_k = a_0 + \frac{1}{[a_1,\dots, a_k]}=\frac{a_0 P_{k-1}(a_1, \dots, a_k) + Q_{k-1}(a_1, \dots, a_k)}{P_{k-1}(a_1, \dots, a_k)}.$$ +$$r_k = a_0 + \frac{1}{[a_1,\dots, a_k]}= a_0 + \frac{Q_{k-1}(a_1, \dots, a_k)}{P_{k-1}(a_1, \dots, a_k)} = \frac{a_0 P_{k-1}(a_1, \dots, a_k) + Q_{k-1}(a_1, \dots, a_k)}{P_{k-1}(a_1, \dots, a_k)}.$$ This gives us the relation $Q_k(a_0, \dots, a_k) = P_{k-1}(a_1, \dots, a_k)$. Therefore, we can focus on the numerator polynomials, as the denominator polynomials can be derived from them. This leads us to the relation @@ -137,9 +139,9 @@ We already know that $r_0 = \frac{a_0}{1}$ and $r_1 = \frac{a_0 a_1 + 1}{a_1}$, $$\begin{align}P_0(a_0)&=a_0,\\ P_1(a_0, a_1) &= a_0 a_1 + 1.\end{align}$$ -For consistency, it is also convenient to define $P_{-1} = 1$ and $P_{-2}=0$, which implies starting points $r_{-1} = \frac{1}{0}$ and $r_{-2}=\frac{0}{1}$. +For consistency, it is convenient to define $P_{-1} = 1$ and $P_{-2}=0$, which implies starting points $r_{-1} = \frac{1}{0}$ and $r_{-2}=\frac{0}{1}$. -#### Continuant +#### The continuant It is a well-known fact in numerical analysis that the determinant of an arbitrary tridiagonal matrix @@ -161,7 +163,7 @@ x_k & 1 & 0 & \dots & 0 \\ 0 & 0 & \dots & -1 & x_0 \end{bmatrix}_{\textstyle .}$$ -This polynomial is also known as [the continuant](https://en.wikipedia.org/wiki/Continuant_(mathematics)) due to its close relation with continued fraction. Noteworthy, the determinant of such matrix won't change if the sequence on the main diagonal is reversed. This gives us the alternative formula to compute continuants: +This polynomial is also known as [the continuant](https://en.wikipedia.org/wiki/Continuant_(mathematics)) due to its close relation with continued fraction. Noteworthy, the determinant of such matrix won't change if the sequence on the main diagonal is reversed. This gives us an alternative formula to compute the continuant: $$P_k(a_0, \dots, a_k) = a_k P_{k-1}(a_0, \dots, a_{k-1}) + P_{k-2}(a_0, \dots, a_{k-2}).$$ @@ -173,27 +175,36 @@ Thus, $r_k$ is a weighted [mediant](https://en.wikipedia.org/wiki/Mediant_(mathe #### Implementation -For the reasons that will be evident as we move further to the geometric interpretation of continued fractions, we will use a [point-like data structure](../geometry/basic-geometry.md) to represent $r_k = \frac{p_k}{q_k}$ as a point $(q_k, p_k)$ on the Euclidean plane. +We will compute the convergents as a pair of sequences $p_{-2}, p_{-1}, p_0, p_1, \dots, p_k$ and $q_{-2}, q_{-1}, q_0, q_1, \dots, q_k$: -```cpp -struct fraction { - ... - - vector convergents() { - vector r = {{1, 0}, {0, 1}}; - for(size_t i = 0; i < a.size(); i++) { - r.push_back(r[i + 1] * a[i] + r[i]); +=== "C++" + ```cpp + auto convergents(vector a) { + vector p = {0, 1}; + vector q = {1, 0}; + for(auto it: a) { + p.push_back(p[p.size() - 1] * it + p[p.size() - 2]); + q.push_back(q[q.size() - 1] * it + q[q.size() - 2]); } - return r; + return make_pair(p, q); } -}; -``` - - + ``` +=== "Python" + ```py + def convergents(a): + p = [0, 1] + q = [1, 0] + for it in a: + p.append(p[-1]*it + p[-2]) + q.append(q[-1]*it + q[-2]) + return p, q + ``` ## Convergence -Let's estimate the distance between $r_k$ and the underlying number $r$. To do this, we start by estimating the difference between adjacent convergents. By definition, it is given with the following formula +_You can mostly skip this section if you're more interested in practical results._ + +Let's estimate the distance between $r_k$ and the underlying number $r$. To do this, we start by estimating the difference between adjacent convergents. By definition, it is given with the following formula: $$\frac{p_k}{q_k} - \frac{p_{k-1}}{q_{k-1}} = \frac{p_k q_{k-1} - p_{k-1} q_k}{q_k q_{k-1}}.$$ @@ -210,13 +221,12 @@ thus $$r_k - r_{k-1} = \frac{(-1)^{k-1}}{q_k q_{k-1}}.$$ - This yields an alternative representation of $r_k$ as a partial sum of infinite series: $$r_k = (r_k - r_{k-1}) + \dots + (r_1 - r_0) + r_0 = a_0 + \sum\limits_{i=1}^k \frac{(-1)^{i-1}}{q_i q_{i-1}}.$$ -From the recurrence relation it follows that $q_k$ monotonously increases at least as fast as Fibonacci numbers, thus +From the recurrent relation it follows that $q_k$ monotonously increases at least as fast as Fibonacci numbers, thus $$r = \lim\limits_{k \to \infty} r_k = a_0 + \sum\limits_{i=1}^\infty \frac{(-1)^{i-1}}{q_i q_{i-1}}$$ @@ -236,7 +246,6 @@ thus the distance between $r$ and $r_k$ is never larger than the distance betwee $$\left|r-\frac{p_k}{q_k}\right| \leq \frac{1}{q_k q_{k+1}} \leq \frac{1}{q_k^2}.$$ - ## Geometric interpretation If convergents $r_0, r_1, \dots$ are treated as 2-dimensional vectors $\vec r_k=(q_k,p_k)$, the mediant formula above turns into From 273333fab6dd20352b92e8f1dca65415713fb745 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Sun, 13 Feb 2022 12:05:03 +0100 Subject: [PATCH 24/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 33bd12cf8..5e6481fa9 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -254,35 +254,35 @@ $$\vec r_k = a_k \vec r_{k-1} + \vec r_{k-2}.$$ To better understand the geometric meaning of $\vec r_k$ we need to look closer into the computation of $a_k$. -### Residuals +### Residues -Previously we investigated the _convergents_ $r_k = [a_0, a_1, \dots, a_k]$. Let's now look on the _residuals_ $s_k = [a_{k}, a_{k+1}, \dots]$. From their definition it holds that +As we have already noted, $a_k = \lfloor s_k \rfloor$, where $s_k = [a_k; a_{k+1}, a_{k+2}, \dots]$. We will get an explicit way to determine $a_k$ if we know how to compute $s_k$. On the other hand, if we formally substitute $s_k$ instead of $a_k$ into the expression for $k$-th convergent, we'll get -$$s_k = a_{k} + \frac{1}{s_{k+1}},$$ +$$r = [a_0, a_1, \dots, a_{k-1}, s_k] = \frac{s_k p_{k-1} + p_{k-2}}{s_k q_{k-1} + q_{k-2}}.$$ -which implies $a_k = \lfloor s_k \rfloor$, so we will get an explicit way to determine $a_k$ if we know how to compute $s_k$. On the other hand, if we formally substitute $a_k$ with $s_k$, that is look on the expression $[a_0, a_1, \dots, a_{k-1}, s_k]$, it will be equal to $r$, thus +From this, we obtain the explicit formula for $s_k$: -$$\vec r = s_k \vec r_{k-1} + \vec r_{k-2},$$ +$$s_k = -\frac{q_{k-2} r - p_{k-2}}{q_{k-1} r - p_{k-1}} = -\frac{q_{k-2}}{q_{k-1}}\frac{r-r_{k-2}}{r-r_{k-1}},$$ -where $\vec r = (1, r)$. Taking cross product of both parts with $\vec r$, we obtain the explicit formula for $s_k$: +or, introducing the vector $\vec r = (1, r)$ and using the notion of the pseudo-scalar product: -$$s_k = -\frac{\vec r \times \vec r_{k-2}}{\vec r \times \vec r_{k-1}}=\left|\frac{\vec r \times \vec r_{k-2}}{\vec r \times \vec r_{k-1}}\right|=\left|\frac{r q_{k-2} - p_{k-2}}{rq_{k-1}-p_{k-1}}\right|=\frac{q_{k-2}}{q_{k-1}}\left|\frac{r -r_{k-2}}{r-r_{k-1}}\right|.$$ +$$s_k = \left|\frac{\vec r_{k-2} \times \vec r}{\vec r_{k-1} \times \vec r}\right|.$$ -Thus, the expression for $\vec r_k$ is given explicitly as +Thus, the expression for $\vec r_k$ is given as $$\vec r_k = \vec r_{k-2} + \left\lfloor \left| \frac{\vec r \times \vec r_{k-2}}{\vec r \times \vec r_{k-1}}\right|\right\rfloor \cdot \vec r_{k-1}.$$ -Note that $\vec r \times \vec r_{k-2}$ and $\vec r \times \vec r_{k-1}$ never have the same sign, as $\vec r_{k-1}$ and $\vec r_{k-2}$ always lie on different size of $\vec r$ due to the fact that their slope coefficients are $r_{k-1}$ and $r_{k-2}$, while the slope coefficient of $\vec r$ is $r$. +Note that $\vec r_{k-1}$ and $\vec r_{k-2}$ generally lie on different sides of $\vec r$, thus $\vec r \times \vec r_{k-2}$ and $\vec r \times \vec r_{k-1}$ have different signs. ### Nose stretching -Geometrically, $a_k$ in the expression above is equal to the maximum integer number of $\vec r_{k-1}$ vectors that can be added to $\vec r_{k-2}$ in such a way that the resulting vector will still be on the same side from $\vec r$ as $\vec r_{k-2}$ is. +Geometrically, $a_k=\lfloor s_k \rfloor$ in the expression above is equal to the maximum integer number of $\vec r_{k-1}$ vectors that can be added to $\vec r_{k-2}$ in such a way that the resulting vector will still be on the same side from $\vec r$ as $\vec r_{k-2}$ is. ![](https://upload.wikimedia.org/wikipedia/commons/9/92/Continued_convergents_geometry.svg) On the picture above you can see how $\vec r_2 = (4,3)$ is obtained by repeatedly adding $\vec r_1 = (1,1)$ to $\vec r_0 = (1, 0)$. When it is not possible to further add $\vec r_1$ to $\vec r_0$ without crossing the $y=rx$ line, we go to the other side and repeatedly add $\vec r_2$ to $\vec r_1$ to obtain $\vec r_3 = (9, 7)$ in a similar manner. -This procedure generates exponentially longer vectors, that approach closer and closer to $y=rx$ line, until one vector is finally collinear with it (when $r$ is rational). For this property, the procedure of generating consequent convergent vectors was dubbed nose stretching algorithm by Boris Delaunay. +This procedure generates exponentially longer vectors, that approach closer and closer to $y=rx$ line, until one vector is finally collinear with it (when $r$ is rational). For this property, the procedure of generating consequent convergent vectors was dubbed the nose stretching algorithm by Boris Delaunay. ### Klein polygons From ad9b13f446cc6c801759610914b213b019b5f93c Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Mon, 14 Feb 2022 20:29:14 +0100 Subject: [PATCH 25/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 66 +++++++++++++++++++++++++++++- 1 file changed, 64 insertions(+), 2 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 5e6481fa9..80ab043b7 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -1,7 +1,7 @@ # Continued fractions in competitive programming -**Continued fraction** is a representation of a real number as a specific convergent sequence of rational numbers. They are useful in competitive programming because they are easy to compute and can be efficiently used to find the best possible approximation of the underlying real number with a rational number (among all numbers whose denominator doesn't exceed a given value). +**Continued fraction** is a representation of a real number as a specific convergent sequence of rational numbers. They are useful in competitive programming because they are easy to compute and can be efficiently used to find the best possible rational approximation of the underlying real number (among all numbers whose denominator doesn't exceed a given value). Besides that, continued fractions are closely related to Euclidean algorithm which makes them useful in a bunch of number-theoretical problems. @@ -294,4 +294,66 @@ Combined with the [Pick's theorem](../geometry/picks-theorem.md), it means that This, in turn, means that $\vec r_k$ with odd coefficients form a convex hull of lattice points with $x \geq 0$ above the line $y=rx$, while $\vec r_k$ with even coefficients form a convex hull of lattice points with $x > 0$ below the line $y=rx$. -These polygons are also known as Klein polygons, named after Felix Klein who first suggested this geometric interpretation to the continued fractions. + +!!! abstract "Definition" + + These polygons are also known as **Klein polygons**, named after Felix Klein who first suggested this geometric interpretation to the continued fractions. + + +!!! abstract "Definition" + + The vectors $\vec r_{k-2} + t \cdot \vec r_{k-1}$ for $0 \leq t \leq a_k$ and corresponding fractions are called the **semi-convergents**. + +Semi-convergent vectors are essentially _all_ lattice vectors on the border of their corresponding convex hulls. + +## Problem examples + +Now that the most important facts and concepts were introduced, it is time to delve into specific problem examples. + +!!! example "[Timus - Crime and Punishment](https://acm.timus.ru/problem.aspx?space=1&num=1430)" + + You're given integer numbers $A$, $B$ and $N$. Find $x \geq 0$ and $y \geq 0$ such that $Ax + By \leq N$ and $Ax + By$ is the maximum possible. + + _Equivalent formulation:_ Given $A$, $B$, $C$ and $N$, find $x$ such that $0 \leq x \leq N$ and $\lfloor \frac{Ax+B}{C} \rfloor$ is the maximum possible. + +??? hint "Solution" + + In the actual problem it holds that $1 \leq A, B, N \leq 2 \cdot 10^9$, so the problem can be solved in $O(\sqrt N)$. + + However, there is $O(\log N)$ solution with continued fractions. + + It is evident that one needs to find the maximum value of $\lfloor \frac{N-Ax}{B} \rfloor$ for $0 \leq x \leq \lfloor \frac{N}{A}\rfloor$. + + For our convenience, we will invert the direction of $x$, so that now we need to find the maximum value of $\lfloor \frac{Ax + \left(N \bmod A \right)}{B} \rfloor$ for $0 \leq x \leq \lfloor \frac{N}{A} \rfloor$. + + To treat it more generically, we will write a function that finds the maximum value of $\lfloor \frac{Ax+B}{C} \rfloor$ on $0 \leq x \leq N$: + + === "C++" + ```cpp + auto solve(int A, int B, int N) { + return max_floor(A, N % A, B, N / A); + } + ``` + === "Python" + ```py + def solve(A, B, N): + x, y = max_rem(A, N % A, B, N // A) + return N // A - x, y + ``` + +!!! example "[CodeChef - Euler Sum](https://www.codechef.com/problems/ES)" + + Compute $\sum\limits_{x=1}^N \lfloor ex \rfloor$, where $e = [2; 1, 2, 1, 1, 4, 1, 1, 6, 1, \dots, 1, 2n, 1, \dots]$ is the Euler's number and $N \leq 10^{4000}$. + + +!!! example "[Kattis - It's a Mod, Mod, Mod, Mod World](https://open.kattis.com/problems/itsamodmodmodmodworld)" + + Given $p$, $q$ and $n$, compute $\sum\limits_{i=1}^n [p \cdot i \bmod q]$. + +The connection between $\bmod$ and $\lfloor \cdot \rfloor$ is given as $a \bmod b = a - \lfloor \frac{a}{b} \rfloor b$. + +!!! example "[Library Checker - Sum of Floor of Linear](https://judge.yosupo.jp/problem/sum_of_floor_of_linear)" + + Given $N$, $M$, $A$ and $B$, compute $\sum\limits_{i=0}^{N-1} \lfloor \frac{A \cdot i + B}{M} \rfloor$. + +This one is a bit more tricky. We'll discuss possible approaches to tackle it further below. From 2a55fff58b30493bfb7a6d9479d7f7284f2c8256 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Mon, 28 Mar 2022 16:26:50 +0200 Subject: [PATCH 26/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 80ab043b7..ab58b07db 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -32,7 +32,7 @@ It can be proven that any rational number can be represented as a continued frac $$r = [a_0;a_1,\dots,a_k,1] = [a_0;a_1,\dots,a_k+1].$$ -Moreover, the length $k$ of continued fraction is bounded as $k = O(\log \min(p, q))$. +Moreover, the length $k$ of such continued fraction is estimated as $k = O(\log \min(p, q))$ for $r=\frac{p}{q}$. The reasoning behind this will be clear once we delve into the details of the continued fraction construction. @@ -66,7 +66,7 @@ The reasoning behind this will be clear once we delve into the details of the co !!! abstract "Definition" - Complementary to convergents, we define the **residues** as $s_k = [a_k; a_{k+1}, a_{k+2}, \dots]$. Correspondingly, we will call an individual $s_k$ the $k$-th residual of $r$. + Complementary to convergents, we define the **residues** as $s_k = [a_k; a_{k+1}, a_{k+2}, \dots]$. Correspondingly, we will call an individual $s_k$ the $k$-th residue of $r$. From the definitions above, one may conclude that $s_k \geq 1$ for $k \geq 1$. If we allow the last term in $[a_0; a_1, \dots, a_k]$ to be an arbitrary real number $s$ and treat it formally as an algebraic expression, the following equation will hold for any $k$: @@ -80,13 +80,19 @@ thus the sequence $a_0, a_1, \dots$ is uniquely defined for any irrational numbe #### Implementation -In the code snippets we will mostly assume that we work with the finite continued fractions. Although continued fractions defined recursively it is more efficient to construct them iteratively. If we start with $s_k=\frac{p}{q}$, the transition looks like +In the code snippets we will mostly assume that we work with the finite continued fractions. Although continued fractions defined recursively, it is more efficient to construct them iteratively. From $s_k$, the transition looks like -$$s_k =\left\lfloor \frac p q \right\rfloor + \frac{1}{s_{k+1}}.$$ +$$s_k =\left\lfloor s_k \right\rfloor + \frac{1}{s_{k+1}}.$$ From this expression, the next residue $s_{k+1}$ is obtained as -$$s_{k+1} = \left(\frac{p}{q}-\left\lfloor \frac{p}{q}\right\rfloor\right)^{-1} = \frac{q}{p-q\cdot \lfloor \frac{p}{q} \rfloor} = \frac{q}{p \bmod q}.$$ +$$s_{k+1} = \left(s_k-\left\lfloor s_k\right\rfloor\right)^{-1}.$$ + +For $s_k=\frac{p}{q}$ it means that + +$$ +s_{k+1} = \frac{q}{p-q\cdot \lfloor \frac{p}{q} \rfloor} = \frac{q}{p \bmod q}. +$$ Thus, computation of a continued fraction representation for $r=\frac{p}{q}$ follows the same steps as the Euclidean algorithm for $p$ and $q$. From 3f0736772d0f85ec09c23cbfbc85410cefbd27e9 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Mon, 28 Mar 2022 17:50:09 +0200 Subject: [PATCH 27/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 47 ++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index ab58b07db..13756d75c 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -117,6 +117,7 @@ Thus, computation of a continued fraction representation for $r=\frac{p}{q}$ fol return a ``` + ### Convergents Let's take a closer look at the convergents that were defined earlier. For $r=[a_0, a_1, a_2, \dots]$, its convergents are @@ -127,6 +128,52 @@ r_0=[a_0],\\r_1=[a_0, a_1],\\ \dots,\\ r_k=[a_0, a_1, \dots, a_k]. It is important to understand how these rational numbers are constructed and how they relate with the underlying number $r$, as they're the main building blocks of everything else related to the continued fraction. +#### Key results + +!!! note "Recurrence" + For the convergents $r_k = \frac{p_k}{q_k}$, the following recurrence stands, allowing their computation: + + $$\frac{p_k}{q_k}=\frac{a_k p_{k-1} + p_{k-2}}{a_k q_{k-1} + q_{k-2}},$$ + + where $\frac{p_{-1}}{q_{-1}}=\frac{1}{0}$ and $\frac{p_{-2}}{q_{-2}}=\frac{0}{1}$. + +!!! note "Deviations" + The deviation of $r_k = \frac{p_k}{q_k}$ from $r$ can be generally estimated as + + $$\left|\frac{p_k}{q_k}-r\right| \leq \frac{1}{q_k q_{k+1}} \leq \frac{1}{q_k^2}.$$ + + Multiplying both sides with $q_k$, we obtain alternate estimation: + + $$|p_k - q_k r| \leq \frac{1}{q_{k+1}}.$$ + +On the picture below you may see the visualization of how convergents $r_k$ approach $r=\frac{1+\sqrt 5}{2}$: + +![](https://upload.wikimedia.org/wikipedia/commons/b/b4/Golden_ration_convergents.svg) + +$r=\frac{1+\sqrt 5}{2}$ is depicted by blue dotted line. Odd convergents approach it from above and even convergents approach it from below. + +!!! note "Lattice hulls" + Consider convex hulls of points above and below the line $y=rx$. + + Odd convergents $(q_k;p_k)$ are the vertices of the upper hull, while the even convergents $(q_k;p_k)$ are the vertices of the bottom hull. + + All integers vertices on the hulls are obtained as $(q;p)$ such that + + $$\frac{p}{q} = \frac{tp_{k-1} + p_{k-2}}{tq_{k-1} + q_{k-2}}$$ + + for integer $0 \leq t \leq a_k$ and are called the **semi-convergents**. + +On the picture below, you may see the convergents and semi-convergents (intermediate gray points) of $r=\frac{9}{7}$. + +![](https://upload.wikimedia.org/wikipedia/commons/9/92/Continued_convergents_geometry.svg) + +!!! note "Best approximations" + Let $\frac{p}{q}$ be the fraction to minimize $\left|r-\frac{p}{q}\right|$ subject to $q \leq x$ for some $x$. + + Then $\frac{p}{q}$ is a semi-convergent of $r$. + +The last fact allows to find the best rational approximations of $r$ by checking its semi-convergents. + #### Recurrent relations The numerator and the denominator of $r_k$ are multivariate polynomials of $a_0, a_1, \dots, a_k$. These polynomials only depend on the number of variables $k$, thus it holds that From e06371b122ae6693132f0c8255c51245f5a72ad9 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Mon, 28 Mar 2022 17:51:25 +0200 Subject: [PATCH 28/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 13756d75c..2384f8759 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -174,6 +174,8 @@ On the picture below, you may see the convergents and semi-convergents (intermed The last fact allows to find the best rational approximations of $r$ by checking its semi-convergents. +Below you will find the further explanation and a bit of intuition and interpretation for these facts. + #### Recurrent relations The numerator and the denominator of $r_k$ are multivariate polynomials of $a_0, a_1, \dots, a_k$. These polynomials only depend on the number of variables $k$, thus it holds that From b3c4de25e8d82a79af871e3c8c3360699bae4734 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Mon, 28 Mar 2022 18:10:15 +0200 Subject: [PATCH 29/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 60 +++++++++++++++--------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 2384f8759..93fb615f8 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -5,9 +5,7 @@ Besides that, continued fractions are closely related to Euclidean algorithm which makes them useful in a bunch of number-theoretical problems. -## Definitions - -### Continued fraction representation +## Continued fraction representation !!! abstract "Definition" @@ -78,7 +76,7 @@ $$s_k = [a_k; s_{k+1}] = a_k + \frac{1}{s_{k+1}} \implies a_k = \lfloor s_k \rfl thus the sequence $a_0, a_1, \dots$ is uniquely defined for any irrational number $r$. -#### Implementation +### Implementation In the code snippets we will mostly assume that we work with the finite continued fractions. Although continued fractions defined recursively, it is more efficient to construct them iteratively. From $s_k$, the transition looks like @@ -117,18 +115,9 @@ Thus, computation of a continued fraction representation for $r=\frac{p}{q}$ fol return a ``` +## Key results -### Convergents - -Let's take a closer look at the convergents that were defined earlier. For $r=[a_0, a_1, a_2, \dots]$, its convergents are - -\begin{gather} -r_0=[a_0],\\r_1=[a_0, a_1],\\ \dots,\\ r_k=[a_0, a_1, \dots, a_k]. -\end{gather} - -It is important to understand how these rational numbers are constructed and how they relate with the underlying number $r$, as they're the main building blocks of everything else related to the continued fraction. - -#### Key results +To provide some motivation for further study of continued fraction, we'll provide some key facts now. !!! note "Recurrence" For the convergents $r_k = \frac{p_k}{q_k}$, the following recurrence stands, allowing their computation: @@ -176,29 +165,39 @@ The last fact allows to find the best rational approximations of $r$ by checking Below you will find the further explanation and a bit of intuition and interpretation for these facts. -#### Recurrent relations +## Convergents + +Let's take a closer look at the convergents that were defined earlier. For $r=[a_0, a_1, a_2, \dots]$, its convergents are + +\begin{gather} +r_0=[a_0],\\r_1=[a_0, a_1],\\ \dots,\\ r_k=[a_0, a_1, \dots, a_k]. +\end{gather} + +It is important to understand how these rational numbers are constructed and how they relate with the underlying number $r$, as they're the main building blocks of everything else related to the continued fraction. + +### Recurrent relations -The numerator and the denominator of $r_k$ are multivariate polynomials of $a_0, a_1, \dots, a_k$. These polynomials only depend on the number of variables $k$, thus it holds that +The numerator and the denominator of $r_k$ can be seen as multivariate polynomials of $a_0, a_1, \dots, a_k$: $$r_k = \frac{P_k(a_0, a_1, \dots, a_k)}{Q_k(a_0,a_1, \dots, a_k)}.$$ -On the other hand, +From the definition of convergents, -$$r_k = a_0 + \frac{1}{[a_1,\dots, a_k]}= a_0 + \frac{Q_{k-1}(a_1, \dots, a_k)}{P_{k-1}(a_1, \dots, a_k)} = \frac{a_0 P_{k-1}(a_1, \dots, a_k) + Q_{k-1}(a_1, \dots, a_k)}{P_{k-1}(a_1, \dots, a_k)}.$$ +$$r_k = a_0 + \frac{1}{[a_1;a_2,\dots, a_k]}= a_0 + \frac{Q_{k-1}(a_1, \dots, a_k)}{P_{k-1}(a_1, \dots, a_k)} = \frac{a_0 P_{k-1}(a_1, \dots, a_k) + Q_{k-1}(a_1, \dots, a_k)}{P_{k-1}(a_1, \dots, a_k)}.$$ -This gives us the relation $Q_k(a_0, \dots, a_k) = P_{k-1}(a_1, \dots, a_k)$. Therefore, we can focus on the numerator polynomials, as the denominator polynomials can be derived from them. This leads us to the relation +From this follows $Q_k(a_0, \dots, a_k) = P_{k-1}(a_1, \dots, a_k)$. This yields the relation $$P_k(a_0, \dots, a_k) = a_0 P_{k-1}(a_1, \dots, a_k) + P_{k-2}(a_2, \dots, a_k).$$ -We already know that $r_0 = \frac{a_0}{1}$ and $r_1 = \frac{a_0 a_1 + 1}{a_1}$, which means that +Initially, $r_0 = \frac{a_0}{1}$ and $r_1 = \frac{a_0 a_1 + 1}{a_1}$, thus $$\begin{align}P_0(a_0)&=a_0,\\ P_1(a_0, a_1) &= a_0 a_1 + 1.\end{align}$$ -For consistency, it is convenient to define $P_{-1} = 1$ and $P_{-2}=0$, which implies starting points $r_{-1} = \frac{1}{0}$ and $r_{-2}=\frac{0}{1}$. +For consistency, it is convenient to define $P_{-1} = 1$ and $P_{-2}=0$ and formally say that $r_{-1} = \frac{1}{0}$ and $r_{-2}=\frac{0}{1}$. -#### The continuant +### The continuant -It is a well-known fact in numerical analysis that the determinant of an arbitrary tridiagonal matrix +From numerical analysis, it is known that the determinant of an arbitrary tridiagonal matrix $$T_k = \det \begin{bmatrix} a_0 & b_0 & 0 & \dots & 0 \\ @@ -208,7 +207,7 @@ c_0 & a_1 & b_1 & \dots & 0 \\ 0 & 0 & \dots & b_{k-1} & a_k \end{bmatrix}$$ -can be computed recursively as $T_k = a_k T_{k-1} - b_{k-1} c_{k-1} T_{k-2}$. Applying this result to $P_k$ yields a direct expression +can be computed recursively as $T_k = a_k T_{k-1} - b_{k-1} c_{k-1} T_{k-2}$. Comparing it to $P_k$, we get a direct expression $$P_k = \det \begin{bmatrix} x_k & 1 & 0 & \dots & 0 \\ @@ -218,17 +217,18 @@ x_k & 1 & 0 & \dots & 0 \\ 0 & 0 & \dots & -1 & x_0 \end{bmatrix}_{\textstyle .}$$ -This polynomial is also known as [the continuant](https://en.wikipedia.org/wiki/Continuant_(mathematics)) due to its close relation with continued fraction. Noteworthy, the determinant of such matrix won't change if the sequence on the main diagonal is reversed. This gives us an alternative formula to compute the continuant: +This polynomial is also known as [the continuant](https://en.wikipedia.org/wiki/Continuant_(mathematics)) due to its close relation with continued fraction. The continuant won't change if the sequence on the main diagonal is reversed. This yields an alternative formula to compute it: $$P_k(a_0, \dots, a_k) = a_k P_{k-1}(a_0, \dots, a_{k-1}) + P_{k-2}(a_0, \dots, a_{k-2}).$$ -This representation is way more convenient, as it shows that $r_k = \frac{p_k}{q_k}$ can be computed as +!!! note "Conclusion" + This representation shows that $r_k = \frac{p_k}{q_k}$ can be computed as -$$r_k = \frac{a_k p_{k-1} + p_{k-2}}{a_k q_{k-1} + q_{k-2}}.$$ + $$r_k = \frac{P_k(a_0,a_1,\dots,a_k)}{P_{k-1}(a_1,\dots,a_k)} = \frac{a_k p_{k-1} + p_{k-2}}{a_k q_{k-1} + q_{k-2}}.$$ -Thus, $r_k$ is a weighted [mediant](https://en.wikipedia.org/wiki/Mediant_(mathematics)) of $r_{k-1}$ and $r_{k-2}$. + Thus, $r_k$ is a weighted [mediant](https://en.wikipedia.org/wiki/Mediant_(mathematics)) of $r_{k-1}$ and $r_{k-2}$. -#### Implementation +### Implementation We will compute the convergents as a pair of sequences $p_{-2}, p_{-1}, p_0, p_1, \dots, p_k$ and $q_{-2}, q_{-1}, q_0, q_1, \dots, q_k$: From 61b4d5efcd2f1c0490d11b87fb93a797d20f5f05 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Mon, 28 Mar 2022 21:57:37 +0200 Subject: [PATCH 30/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 111 +++++++++++++++++------------ 1 file changed, 65 insertions(+), 46 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 93fb615f8..11c3bfbe4 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -8,7 +8,6 @@ Besides that, continued fractions are closely related to Euclidean algorithm whi ## Continued fraction representation !!! abstract "Definition" - Let $a_0, a_1, \dots, a_k \in \mathbb Z$ and $a_1, a_2, \dots, a_k \geq 1$. Then the expression $$r=a_0 + \frac{1}{a_1 + \frac{1}{\dots + \frac{1}{a_k}}},$$ @@ -16,7 +15,6 @@ Besides that, continued fractions are closely related to Euclidean algorithm whi is called the **continued fraction representation** of the rational number $r$ and is denoted shortly as $r=[a_0;a_1,a_2,\dots,a_k]$. ??? example - Let $r = \frac{5}{3}$. There are two ways to represent it as a continued fraction: $$ @@ -35,7 +33,6 @@ Moreover, the length $k$ of such continued fraction is estimated as $k = O(\log The reasoning behind this will be clear once we delve into the details of the continued fraction construction. !!! abstract "Definition" - Let $a_0,a_1,a_2, \dots$ be an integer sequence such that $a_1, a_2, \dots \geq 1$. Let $r_k = [a_0; a_1, \dots, a_k]$. Then the expression $$r = a_0 + \frac{1}{a_1 + \frac{1}{a_2+\dots}} = \lim\limits_{k \to \infty} r_k.$$ @@ -43,13 +40,11 @@ The reasoning behind this will be clear once we delve into the details of the co is called the **continued fraction representation** of the irrational number $r$ and is denoted shortly as $r = [a_0;a_1,a_2,\dots]$. !!! abstract "Definition" - In the definition above, rational numbers $r_0, r_1, r_2, \dots$ are called the **convergents** of $r$. Correspondingly, individual $r_k = [a_0; a_1, \dots, a_k]$ is called the $k$-th **convergent** of $r$. ??? example - Consider $r = [1; 1, 1, 1, \dots]$. It can be proven by induction that $r_k = \frac{F_{k+2}}{F_{k+1}}$, where $F_k$ is the Fibonacci sequence defined as $F_0 = 0$, $F_1 = 1$ and $F_{k} = F_{k-1} + F_{k-2}$. From the Binet's formula, it is known that $$r_k = \frac{\phi^{k+2} - \psi^{k+2}}{\phi^{k+1} - \psi^{k+1}},$$ @@ -62,8 +57,11 @@ The reasoning behind this will be clear once we delve into the details of the co $$r = 1+\frac{1}{r} \implies r^2 = r + 1. $$ + !!! abstract "Definition" + Let $r_k = [a_0; a_1, \dots, a_k]$. The numbers $[a_0; a_1, \dots, t]$ for $1 \leq t \leq a_k$ are called **semiconvergents**. +!!! abstract "Definition" Complementary to convergents, we define the **residues** as $s_k = [a_k; a_{k+1}, a_{k+2}, \dots]$. Correspondingly, we will call an individual $s_k$ the $k$-th residue of $r$. From the definitions above, one may conclude that $s_k \geq 1$ for $k \geq 1$. If we allow the last term in $[a_0; a_1, \dots, a_k]$ to be an arbitrary real number $s$ and treat it formally as an algebraic expression, the following equation will hold for any $k$: @@ -78,7 +76,7 @@ thus the sequence $a_0, a_1, \dots$ is uniquely defined for any irrational numbe ### Implementation -In the code snippets we will mostly assume that we work with the finite continued fractions. Although continued fractions defined recursively, it is more efficient to construct them iteratively. From $s_k$, the transition looks like +In the code snippets we will mostly assume that we work with the finite continued fractions. Although continued fractions are defined recursively, it is more efficient to construct them iteratively. From $s_k$, the transition looks like $$s_k =\left\lfloor s_k \right\rfloor + \frac{1}{s_{k+1}}.$$ @@ -89,7 +87,7 @@ $$s_{k+1} = \left(s_k-\left\lfloor s_k\right\rfloor\right)^{-1}.$$ For $s_k=\frac{p}{q}$ it means that $$ -s_{k+1} = \frac{q}{p-q\cdot \lfloor \frac{p}{q} \rfloor} = \frac{q}{p \bmod q}. +s_{k+1} = \left(\frac{p}{q}-\left\lfloor \frac{p}{q} \right\rfloor\right)^{-1} = \frac{q}{p-q\cdot \lfloor \frac{p}{q} \rfloor} = \frac{q}{p \bmod q}. $$ Thus, computation of a continued fraction representation for $r=\frac{p}{q}$ follows the same steps as the Euclidean algorithm for $p$ and $q$. @@ -117,16 +115,16 @@ Thus, computation of a continued fraction representation for $r=\frac{p}{q}$ fol ## Key results -To provide some motivation for further study of continued fraction, we'll provide some key facts now. +To provide some motivation for further study of continued fraction, we give some key facts now. -!!! note "Recurrence" - For the convergents $r_k = \frac{p_k}{q_k}$, the following recurrence stands, allowing their computation: +??? note "Recurrence" + For the convergents $r_k = \frac{p_k}{q_k}$, the following recurrence stands, allowing their fast computation: $$\frac{p_k}{q_k}=\frac{a_k p_{k-1} + p_{k-2}}{a_k q_{k-1} + q_{k-2}},$$ where $\frac{p_{-1}}{q_{-1}}=\frac{1}{0}$ and $\frac{p_{-2}}{q_{-2}}=\frac{0}{1}$. -!!! note "Deviations" +??? note "Deviations" The deviation of $r_k = \frac{p_k}{q_k}$ from $r$ can be generally estimated as $$\left|\frac{p_k}{q_k}-r\right| \leq \frac{1}{q_k q_{k+1}} \leq \frac{1}{q_k^2}.$$ @@ -135,13 +133,15 @@ To provide some motivation for further study of continued fraction, we'll provid $$|p_k - q_k r| \leq \frac{1}{q_{k+1}}.$$ -On the picture below you may see the visualization of how convergents $r_k$ approach $r=\frac{1+\sqrt 5}{2}$: + From the recurrence above it follows that $q_k$ grows at least as fast as Fibonacci numbers. -![](https://upload.wikimedia.org/wikipedia/commons/b/b4/Golden_ration_convergents.svg) + On the picture below you may see the visualization of how convergents $r_k$ approach $r=\frac{1+\sqrt 5}{2}$: -$r=\frac{1+\sqrt 5}{2}$ is depicted by blue dotted line. Odd convergents approach it from above and even convergents approach it from below. + ![](https://upload.wikimedia.org/wikipedia/commons/b/b4/Golden_ration_convergents.svg) -!!! note "Lattice hulls" + $r=\frac{1+\sqrt 5}{2}$ is depicted by blue dotted line. Odd convergents approach it from above and even convergents approach it from below. + +??? note "Lattice hulls" Consider convex hulls of points above and below the line $y=rx$. Odd convergents $(q_k;p_k)$ are the vertices of the upper hull, while the even convergents $(q_k;p_k)$ are the vertices of the bottom hull. @@ -150,18 +150,18 @@ $r=\frac{1+\sqrt 5}{2}$ is depicted by blue dotted line. Odd convergents approac $$\frac{p}{q} = \frac{tp_{k-1} + p_{k-2}}{tq_{k-1} + q_{k-2}}$$ - for integer $0 \leq t \leq a_k$ and are called the **semi-convergents**. + for integer $0 \leq t \leq a_k$. In other words, the set of lattice points on the hulls corresponds to the set of semiconvergents. -On the picture below, you may see the convergents and semi-convergents (intermediate gray points) of $r=\frac{9}{7}$. + On the picture below, you may see the convergents and semiconvergents (intermediate gray points) of $r=\frac{9}{7}$. -![](https://upload.wikimedia.org/wikipedia/commons/9/92/Continued_convergents_geometry.svg) + ![](https://upload.wikimedia.org/wikipedia/commons/9/92/Continued_convergents_geometry.svg) -!!! note "Best approximations" +??? note "Best approximations" Let $\frac{p}{q}$ be the fraction to minimize $\left|r-\frac{p}{q}\right|$ subject to $q \leq x$ for some $x$. - Then $\frac{p}{q}$ is a semi-convergent of $r$. + Then $\frac{p}{q}$ is a semiconvergent of $r$. -The last fact allows to find the best rational approximations of $r$ by checking its semi-convergents. +The last fact allows to find the best rational approximations of $r$ by checking its semiconvergents. Below you will find the further explanation and a bit of intuition and interpretation for these facts. @@ -173,7 +173,7 @@ Let's take a closer look at the convergents that were defined earlier. For $r=[a r_0=[a_0],\\r_1=[a_0, a_1],\\ \dots,\\ r_k=[a_0, a_1, \dots, a_k]. \end{gather} -It is important to understand how these rational numbers are constructed and how they relate with the underlying number $r$, as they're the main building blocks of everything else related to the continued fraction. +Convergents are the core concept of continued fractions, so it is important to study their properties. ### Recurrent relations @@ -259,47 +259,66 @@ We will compute the convergents as a pair of sequences $p_{-2}, p_{-1}, p_0, p_1 _You can mostly skip this section if you're more interested in practical results._ -Let's estimate the distance between $r_k$ and the underlying number $r$. To do this, we start by estimating the difference between adjacent convergents. By definition, it is given with the following formula: +!!! note "Convergence rate" + For the number $r$ and its $k$-th convergent $r_k=\frac{p_k}{q_k}$ the following formula stand: + + $$r_k = a_0 + \sum\limits_{i=1}^k \frac{(-1)^{i-1}}{q_i q_{i-1}}.$$ + + In particular, + + $$r_k - r_{k-1} = \frac{(-1)^{k-1}}{q_k q_{k-1}}$$ + + and + + $$\left| r-\frac{p_k}{q_k} \right| \leq \frac{1}{q_{k+1}q_k} \leq \frac{1}{q_k^2}.$$ + + The latter inequality is due to the fact that $r_k$ and $r_{k+1}$ are generally located on different sides of $r$, thus + + $$|r-r_k| = |r_k-r_{k+1}|-|r-r_{k+1}| \leq |r_k - r_{k+1}|.$$ + +??? tip "Detailed explanation" + + To estimate $|r-r_k|$, we start by estimating the difference between adjacent convergents. By definition, -$$\frac{p_k}{q_k} - \frac{p_{k-1}}{q_{k-1}} = \frac{p_k q_{k-1} - p_{k-1} q_k}{q_k q_{k-1}}.$$ + $$\frac{p_k}{q_k} - \frac{p_{k-1}}{q_{k-1}} = \frac{p_k q_{k-1} - p_{k-1} q_k}{q_k q_{k-1}}.$$ -Replacing $p_k$ and $q_k$ in the numerator with their recurrences, we get + Replacing $p_k$ and $q_k$ in the numerator with their recurrences, we get -$$\begin{align} p_k q_{k-1} - p_{k-1} q_k &= (a_k p_{k-1} + p_{k-2}) q_{k-1} - p_{k-1} (a_k q_{k-1} + q_{k-2}) -\\&= p_{k-2} q_{k-1} - p_{k-1} q_{k-2},\end{align}$$ + $$\begin{align} p_k q_{k-1} - p_{k-1} q_k &= (a_k p_{k-1} + p_{k-2}) q_{k-1} - p_{k-1} (a_k q_{k-1} + q_{k-2}) + \\&= p_{k-2} q_{k-1} - p_{k-1} q_{k-2},\end{align}$$ -thus the numerator of $r_k - r_{k-1}$ is always the negated numerator of $r_{k-1} - r_{k-2}$. It, in turn, equals to $1$ for + thus the numerator of $r_k - r_{k-1}$ is always the negated numerator of $r_{k-1} - r_{k-2}$. It, in turn, equals to $1$ for -$$r_1 - r_0=\left(a_0+\frac{1}{a_1}\right)-a_0=\frac{1}{a_1},$$ + $$r_1 - r_0=\left(a_0+\frac{1}{a_1}\right)-a_0=\frac{1}{a_1},$$ -thus + thus -$$r_k - r_{k-1} = \frac{(-1)^{k-1}}{q_k q_{k-1}}.$$ + $$r_k - r_{k-1} = \frac{(-1)^{k-1}}{q_k q_{k-1}}.$$ -This yields an alternative representation of $r_k$ as a partial sum of infinite series: + This yields an alternative representation of $r_k$ as a partial sum of infinite series: -$$r_k = (r_k - r_{k-1}) + \dots + (r_1 - r_0) + r_0 -= a_0 + \sum\limits_{i=1}^k \frac{(-1)^{i-1}}{q_i q_{i-1}}.$$ + $$r_k = (r_k - r_{k-1}) + \dots + (r_1 - r_0) + r_0 + = a_0 + \sum\limits_{i=1}^k \frac{(-1)^{i-1}}{q_i q_{i-1}}.$$ -From the recurrent relation it follows that $q_k$ monotonously increases at least as fast as Fibonacci numbers, thus + From the recurrent relation it follows that $q_k$ monotonously increases at least as fast as Fibonacci numbers, thus -$$r = \lim\limits_{k \to \infty} r_k = a_0 + \sum\limits_{i=1}^\infty \frac{(-1)^{i-1}}{q_i q_{i-1}}$$ + $$r = \lim\limits_{k \to \infty} r_k = a_0 + \sum\limits_{i=1}^\infty \frac{(-1)^{i-1}}{q_i q_{i-1}}$$ -is always well-defined, as the underlying series always converge. Noteworthy, the residual series + is always well-defined, as the underlying series always converge. Noteworthy, the residual series -$$r-r_k = \sum\limits_{i=k+1}^\infty \frac{(-1)^{i-1}}{q_i q_{i-1}}$$ + $$r-r_k = \sum\limits_{i=k+1}^\infty \frac{(-1)^{i-1}}{q_i q_{i-1}}$$ -has the same sign as $(-1)^k$ due to how fast $q_i q_{i-1}$ decreases. It means that even-indexed $r_k$ monotonously approach $r$ from below while odd-indexed $r_k$ monotonously approach it from above: + has the same sign as $(-1)^k$ due to how fast $q_i q_{i-1}$ decreases. It means that even-indexed $r_k$ monotonously approach $r$ from below while odd-indexed $r_k$ monotonously approach it from above: -![](https://upload.wikimedia.org/wikipedia/commons/b/b4/Golden_ration_convergents.svg) + ![](https://upload.wikimedia.org/wikipedia/commons/b/b4/Golden_ration_convergents.svg) -From this picture we can see that + From this picture we can see that -$$|r-r_k| = |r_k - r_{k+1}| - |r-r_{k+1}| \leq |r_k - r_{k+1}|,$$ + $$|r-r_k| = |r_k - r_{k+1}| - |r-r_{k+1}| \leq |r_k - r_{k+1}|,$$ -thus the distance between $r$ and $r_k$ is never larger than the distance between $r_k$ and $r_{k+1}$: + thus the distance between $r$ and $r_k$ is never larger than the distance between $r_k$ and $r_{k+1}$: -$$\left|r-\frac{p_k}{q_k}\right| \leq \frac{1}{q_k q_{k+1}} \leq \frac{1}{q_k^2}.$$ + $$\left|r-\frac{p_k}{q_k}\right| \leq \frac{1}{q_k q_{k+1}} \leq \frac{1}{q_k^2}.$$ ## Geometric interpretation @@ -357,9 +376,9 @@ This, in turn, means that $\vec r_k$ with odd coefficients form a convex hull of !!! abstract "Definition" - The vectors $\vec r_{k-2} + t \cdot \vec r_{k-1}$ for $0 \leq t \leq a_k$ and corresponding fractions are called the **semi-convergents**. + The vectors $\vec r_{k-2} + t \cdot \vec r_{k-1}$ for $0 \leq t \leq a_k$ and corresponding fractions are called the **semiconvergents**. -Semi-convergent vectors are essentially _all_ lattice vectors on the border of their corresponding convex hulls. +Semiconvergent vectors are essentially _all_ lattice vectors on the border of their corresponding convex hulls. ## Problem examples From dcdd69d46d67b18432008b5d011f4ad96710c3de Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Mon, 28 Mar 2022 22:02:45 +0200 Subject: [PATCH 31/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 68 +++++++++++++++--------------- 1 file changed, 33 insertions(+), 35 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 11c3bfbe4..50114f8b4 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -175,58 +175,56 @@ r_0=[a_0],\\r_1=[a_0, a_1],\\ \dots,\\ r_k=[a_0, a_1, \dots, a_k]. Convergents are the core concept of continued fractions, so it is important to study their properties. -### Recurrent relations +!!! note "Recurrence" + For the number $r$, its $k$-th convergent $r_k = \frac{p_k}{q_k}$ can be computed as -The numerator and the denominator of $r_k$ can be seen as multivariate polynomials of $a_0, a_1, \dots, a_k$: + $$r_k = \frac{P_k(a_0,a_1,\dots,a_k)}{P_{k-1}(a_1,\dots,a_k)} = \frac{a_k p_{k-1} + p_{k-2}}{a_k q_{k-1} + q_{k-2}}.$$ -$$r_k = \frac{P_k(a_0, a_1, \dots, a_k)}{Q_k(a_0,a_1, \dots, a_k)}.$$ + Thus, $r_k$ is a weighted [mediant](https://en.wikipedia.org/wiki/Mediant_(mathematics)) of $r_{k-1}$ and $r_{k-2}$. -From the definition of convergents, +??? hint "Detailed explanation" -$$r_k = a_0 + \frac{1}{[a_1;a_2,\dots, a_k]}= a_0 + \frac{Q_{k-1}(a_1, \dots, a_k)}{P_{k-1}(a_1, \dots, a_k)} = \frac{a_0 P_{k-1}(a_1, \dots, a_k) + Q_{k-1}(a_1, \dots, a_k)}{P_{k-1}(a_1, \dots, a_k)}.$$ + The numerator and the denominator of $r_k$ can be seen as multivariate polynomials of $a_0, a_1, \dots, a_k$: -From this follows $Q_k(a_0, \dots, a_k) = P_{k-1}(a_1, \dots, a_k)$. This yields the relation + $$r_k = \frac{P_k(a_0, a_1, \dots, a_k)}{Q_k(a_0,a_1, \dots, a_k)}.$$ -$$P_k(a_0, \dots, a_k) = a_0 P_{k-1}(a_1, \dots, a_k) + P_{k-2}(a_2, \dots, a_k).$$ + From the definition of convergents, -Initially, $r_0 = \frac{a_0}{1}$ and $r_1 = \frac{a_0 a_1 + 1}{a_1}$, thus + $$r_k = a_0 + \frac{1}{[a_1;a_2,\dots, a_k]}= a_0 + \frac{Q_{k-1}(a_1, \dots, a_k)}{P_{k-1}(a_1, \dots, a_k)} = \frac{a_0 P_{k-1}(a_1, \dots, a_k) + Q_{k-1}(a_1, \dots, a_k)}{P_{k-1}(a_1, \dots, a_k)}.$$ -$$\begin{align}P_0(a_0)&=a_0,\\ P_1(a_0, a_1) &= a_0 a_1 + 1.\end{align}$$ + From this follows $Q_k(a_0, \dots, a_k) = P_{k-1}(a_1, \dots, a_k)$. This yields the relation -For consistency, it is convenient to define $P_{-1} = 1$ and $P_{-2}=0$ and formally say that $r_{-1} = \frac{1}{0}$ and $r_{-2}=\frac{0}{1}$. + $$P_k(a_0, \dots, a_k) = a_0 P_{k-1}(a_1, \dots, a_k) + P_{k-2}(a_2, \dots, a_k).$$ -### The continuant + Initially, $r_0 = \frac{a_0}{1}$ and $r_1 = \frac{a_0 a_1 + 1}{a_1}$, thus -From numerical analysis, it is known that the determinant of an arbitrary tridiagonal matrix + $$\begin{align}P_0(a_0)&=a_0,\\ P_1(a_0, a_1) &= a_0 a_1 + 1.\end{align}$$ -$$T_k = \det \begin{bmatrix} -a_0 & b_0 & 0 & \dots & 0 \\ -c_0 & a_1 & b_1 & \dots & 0 \\ -0 & c_1 & a_2 & . & \vdots \\ -\vdots & \vdots & . & \ddots & c_{k-1} \\ -0 & 0 & \dots & b_{k-1} & a_k -\end{bmatrix}$$ + For consistency, it is convenient to define $P_{-1} = 1$ and $P_{-2}=0$ and formally say that $r_{-1} = \frac{1}{0}$ and $r_{-2}=\frac{0}{1}$. -can be computed recursively as $T_k = a_k T_{k-1} - b_{k-1} c_{k-1} T_{k-2}$. Comparing it to $P_k$, we get a direct expression + From numerical analysis, it is known that the determinant of an arbitrary tridiagonal matrix -$$P_k = \det \begin{bmatrix} -x_k & 1 & 0 & \dots & 0 \\ --1 & x_{k-1} & 1 & \dots & 0 \\ -0 & -1 & x_2 & . & \vdots \\ -\vdots & \vdots & . & \ddots & 1 \\ -0 & 0 & \dots & -1 & x_0 -\end{bmatrix}_{\textstyle .}$$ + $$T_k = \det \begin{bmatrix} + a_0 & b_0 & 0 & \dots & 0 \\ + c_0 & a_1 & b_1 & \dots & 0 \\ + 0 & c_1 & a_2 & . & \vdots \\ + \vdots & \vdots & . & \ddots & c_{k-1} \\ + 0 & 0 & \dots & b_{k-1} & a_k + \end{bmatrix}$$ -This polynomial is also known as [the continuant](https://en.wikipedia.org/wiki/Continuant_(mathematics)) due to its close relation with continued fraction. The continuant won't change if the sequence on the main diagonal is reversed. This yields an alternative formula to compute it: + can be computed recursively as $T_k = a_k T_{k-1} - b_{k-1} c_{k-1} T_{k-2}$. Comparing it to $P_k$, we get a direct expression -$$P_k(a_0, \dots, a_k) = a_k P_{k-1}(a_0, \dots, a_{k-1}) + P_{k-2}(a_0, \dots, a_{k-2}).$$ + $$P_k = \det \begin{bmatrix} + x_k & 1 & 0 & \dots & 0 \\ + -1 & x_{k-1} & 1 & \dots & 0 \\ + 0 & -1 & x_2 & . & \vdots \\ + \vdots & \vdots & . & \ddots & 1 \\ + 0 & 0 & \dots & -1 & x_0 + \end{bmatrix}_{\textstyle .}$$ -!!! note "Conclusion" - This representation shows that $r_k = \frac{p_k}{q_k}$ can be computed as + This polynomial is also known as [the continuant](https://en.wikipedia.org/wiki/Continuant_(mathematics)) due to its close relation with continued fraction. The continuant won't change if the sequence on the main diagonal is reversed. This yields an alternative formula to compute it: - $$r_k = \frac{P_k(a_0,a_1,\dots,a_k)}{P_{k-1}(a_1,\dots,a_k)} = \frac{a_k p_{k-1} + p_{k-2}}{a_k q_{k-1} + q_{k-2}}.$$ - - Thus, $r_k$ is a weighted [mediant](https://en.wikipedia.org/wiki/Mediant_(mathematics)) of $r_{k-1}$ and $r_{k-2}$. + $$P_k(a_0, \dots, a_k) = a_k P_{k-1}(a_0, \dots, a_{k-1}) + P_{k-2}(a_0, \dots, a_{k-2}).$$ ### Implementation @@ -260,7 +258,7 @@ We will compute the convergents as a pair of sequences $p_{-2}, p_{-1}, p_0, p_1 _You can mostly skip this section if you're more interested in practical results._ !!! note "Convergence rate" - For the number $r$ and its $k$-th convergent $r_k=\frac{p_k}{q_k}$ the following formula stand: + For the number $r$ and its $k$-th convergent $r_k=\frac{p_k}{q_k}$ the following formula stands: $$r_k = a_0 + \sum\limits_{i=1}^k \frac{(-1)^{i-1}}{q_i q_{i-1}}.$$ From 5f10cc9cbc21e8bca360fb03d9561caac8e3cd78 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Tue, 29 Mar 2022 01:00:39 +0200 Subject: [PATCH 32/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 68 ++++++++++++++++++++---------- 1 file changed, 46 insertions(+), 22 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 50114f8b4..a4cb2db14 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -24,13 +24,15 @@ Besides that, continued fractions are closely related to Euclidean algorithm whi \end{align} $$ -It can be proven that any rational number can be represented as a continued fraction in exactly $2$ ways: +!!! note "Different representations and representation length for rational numbers" -$$r = [a_0;a_1,\dots,a_k,1] = [a_0;a_1,\dots,a_k+1].$$ + It can be proven that any rational number can be represented as a continued fraction in exactly $2$ ways: -Moreover, the length $k$ of such continued fraction is estimated as $k = O(\log \min(p, q))$ for $r=\frac{p}{q}$. + $$r = [a_0;a_1,\dots,a_k,1] = [a_0;a_1,\dots,a_k+1].$$ -The reasoning behind this will be clear once we delve into the details of the continued fraction construction. + Moreover, the length $k$ of such continued fraction is estimated as $k = O(\log \min(p, q))$ for $r=\frac{p}{q}$. + + The reasoning behind this will be clear once we delve into the details of the continued fraction construction. !!! abstract "Definition" Let $a_0,a_1,a_2, \dots$ be an integer sequence such that $a_1, a_2, \dots \geq 1$. Let $r_k = [a_0; a_1, \dots, a_k]$. Then the expression @@ -64,33 +66,44 @@ The reasoning behind this will be clear once we delve into the details of the co !!! abstract "Definition" Complementary to convergents, we define the **residues** as $s_k = [a_k; a_{k+1}, a_{k+2}, \dots]$. Correspondingly, we will call an individual $s_k$ the $k$-th residue of $r$. -From the definitions above, one may conclude that $s_k \geq 1$ for $k \geq 1$. If we allow the last term in $[a_0; a_1, \dots, a_k]$ to be an arbitrary real number $s$ and treat it formally as an algebraic expression, the following equation will hold for any $k$: +!!! note "Connection between residues and continued fraction representation" + + From the definitions above, $s_k \geq 1$ for $k \geq 1$. + + Let's treat $[a_0; a_1, \dots, a_k]$ as a formal algebraic expression and allow arbitrary real numbers instead of $a_i$, then, by definition, + + $$r = [a_0; a_1, \dots, a_{k-1}, s_k].$$ -$$r = [a_0; a_1, \dots, a_{k-1}, s_k],$$ + In particular, $r = [s_0] = s_0$. On the other hand, we can express $s_k$ as -in particular $r = [s_0] = s_0$. This, in turn, allows us to deduct that + $$s_k = [a_k; s_{k+1}] = a_k + \frac{1}{s_{k+1}},$$ -$$s_k = [a_k; s_{k+1}] = a_k + \frac{1}{s_{k+1}} \implies a_k = \lfloor s_k \rfloor,$$ + meaning that we can compute $a_k = \lfloor s_k \rfloor$ and $s_{k+1} = (s_k - a_k)^{-1}$ from $s_k$. -thus the sequence $a_0, a_1, \dots$ is uniquely defined for any irrational number $r$. + The sequence $a_0, a_1, \dots$ is well-defined unless $s_k=a_k$ which only happens when $r$ is a rational number. + + Thus the continued fraction representation is uniquely defined for any irrational number $r$. ### Implementation -In the code snippets we will mostly assume that we work with the finite continued fractions. Although continued fractions are defined recursively, it is more efficient to construct them iteratively. From $s_k$, the transition looks like +In the code snippets we will mostly assume finite continued fractions. + +!!! note "Transition formulas" + From $s_k$, the transition to $s_{k+1}$ looks like -$$s_k =\left\lfloor s_k \right\rfloor + \frac{1}{s_{k+1}}.$$ + $$s_k =\left\lfloor s_k \right\rfloor + \frac{1}{s_{k+1}}.$$ -From this expression, the next residue $s_{k+1}$ is obtained as + From this expression, the next residue $s_{k+1}$ is obtained as -$$s_{k+1} = \left(s_k-\left\lfloor s_k\right\rfloor\right)^{-1}.$$ + $$s_{k+1} = \left(s_k-\left\lfloor s_k\right\rfloor\right)^{-1}.$$ -For $s_k=\frac{p}{q}$ it means that + For $s_k=\frac{p}{q}$ it means that -$$ -s_{k+1} = \left(\frac{p}{q}-\left\lfloor \frac{p}{q} \right\rfloor\right)^{-1} = \frac{q}{p-q\cdot \lfloor \frac{p}{q} \rfloor} = \frac{q}{p \bmod q}. -$$ + $$ + s_{k+1} = \left(\frac{p}{q}-\left\lfloor \frac{p}{q} \right\rfloor\right)^{-1} = \frac{q}{p-q\cdot \lfloor \frac{p}{q} \rfloor} = \frac{q}{p \bmod q}. + $$ -Thus, computation of a continued fraction representation for $r=\frac{p}{q}$ follows the same steps as the Euclidean algorithm for $p$ and $q$. + Thus, computation of a continued fraction representation for $r=\frac{p}{q}$ follows the same steps as the Euclidean algorithm for $p$ and $q$. === "C++" ```cpp @@ -178,7 +191,17 @@ Convergents are the core concept of continued fractions, so it is important to s !!! note "Recurrence" For the number $r$, its $k$-th convergent $r_k = \frac{p_k}{q_k}$ can be computed as - $$r_k = \frac{P_k(a_0,a_1,\dots,a_k)}{P_{k-1}(a_1,\dots,a_k)} = \frac{a_k p_{k-1} + p_{k-2}}{a_k q_{k-1} + q_{k-2}}.$$ + $$r_k = \frac{P_k(a_0,a_1,\dots,a_k)}{P_{k-1}(a_1,\dots,a_k)} = \frac{a_k p_{k-1} + p_{k-2}}{a_k q_{k-1} + q_{k-2}},$$ + + where $P_k(a_0,\dots,a_k)$ is [the continuant](https://en.wikipedia.org/wiki/Continuant_(mathematics)), a multivariate polynomial defined as + + $$P_k(x_0,x_1,\dots,x_k) = \det \begin{bmatrix} + x_k & 1 & 0 & \dots & 0 \\ + -1 & x_{k-1} & 1 & \dots & 0 \\ + 0 & -1 & x_2 & . & \vdots \\ + \vdots & \vdots & . & \ddots & 1 \\ + 0 & 0 & \dots & -1 & x_0 + \end{bmatrix}_{\textstyle .}$$ Thus, $r_k$ is a weighted [mediant](https://en.wikipedia.org/wiki/Mediant_(mathematics)) of $r_{k-1}$ and $r_{k-2}$. @@ -320,11 +343,12 @@ _You can mostly skip this section if you're more interested in practical results ## Geometric interpretation -If convergents $r_0, r_1, \dots$ are treated as 2-dimensional vectors $\vec r_k=(q_k,p_k)$, the mediant formula above turns into +!!! note "Numbers as vectors" + Let $\vec r_k = (q_k;p_k)$ for the convergent $r_k = \frac{p_k}{q_k}$. Then, the following recurrence holds: -$$\vec r_k = a_k \vec r_{k-1} + \vec r_{k-2}.$$ + $$\vec r_k = a_k \vec r_{k-1} + \vec r_{k-2}.$$ -To better understand the geometric meaning of $\vec r_k$ we need to look closer into the computation of $a_k$. + We additionally define $\vec r = (1;r)$. In these terms, each vector $(x;y)$ corresponds to the number that is equal to its slope coefficient $\frac{y}{x}$. ### Residues From 619b8116bf2f86e03ffe059f05deb2035979977a Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Tue, 29 Mar 2022 02:37:49 +0200 Subject: [PATCH 33/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 62 ++++++++++++++++++------------ 1 file changed, 37 insertions(+), 25 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index a4cb2db14..3c4d25e03 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -350,57 +350,69 @@ _You can mostly skip this section if you're more interested in practical results We additionally define $\vec r = (1;r)$. In these terms, each vector $(x;y)$ corresponds to the number that is equal to its slope coefficient $\frac{y}{x}$. -### Residues +!!! note "Formulas for $a_k$ and $s_k$ in terms of convergents" + With the notion of [pseudoscalar product](../geometry/basic-geometry.md) $(x_1;y_1) \times (x_2;y_2) = x_1 y_2 - x_2 y_1$, it can be shown (see the explanation below) that -As we have already noted, $a_k = \lfloor s_k \rfloor$, where $s_k = [a_k; a_{k+1}, a_{k+2}, \dots]$. We will get an explicit way to determine $a_k$ if we know how to compute $s_k$. On the other hand, if we formally substitute $s_k$ instead of $a_k$ into the expression for $k$-th convergent, we'll get + $$s_k = -\frac{\vec r_{k-2} \times \vec r}{\vec r_{k-1} \times \vec r} = \left|\frac{\vec r_{k-2} \times \vec r}{\vec r_{k-1} \times \vec r}\right|.$$ -$$r = [a_0, a_1, \dots, a_{k-1}, s_k] = \frac{s_k p_{k-1} + p_{k-2}}{s_k q_{k-1} + q_{k-2}}.$$ + The last equation is due to the fact that $r_{k-1}$ and $r_{k-2}$ lie on the different sides of $r$, thus pseudoscalar products of $\vec r_{k-1}$ and $\vec r_{k-2}$ with $\vec r$ have distinct signs. -From this, we obtain the explicit formula for $s_k$: + With $a_k = \lfloor s_k \rfloor$ in mind, formula for $\vec r_k$ now looks like -$$s_k = -\frac{q_{k-2} r - p_{k-2}}{q_{k-1} r - p_{k-1}} = -\frac{q_{k-2}}{q_{k-1}}\frac{r-r_{k-2}}{r-r_{k-1}},$$ + $$\vec r_k = \vec r_{k-2} + \left\lfloor \left| \frac{\vec r \times \vec r_{k-2}}{\vec r \times \vec r_{k-1}}\right|\right\rfloor \vec r_{k-1}.$$ -or, introducing the vector $\vec r = (1, r)$ and using the notion of the pseudo-scalar product: + Note that $\vec r_k \times r = (q;p) \times (1;r) = qr - p$, thus -$$s_k = \left|\frac{\vec r_{k-2} \times \vec r}{\vec r_{k-1} \times \vec r}\right|.$$ + $$a_k = \left\lfloor \left| \frac{q_{k-1}r-p_{k-1}}{q_{k-2}r-p_{k-2}} \right| \right\rfloor.$$ -Thus, the expression for $\vec r_k$ is given as +??? hint "Explanation" + As we have already noted, $a_k = \lfloor s_k \rfloor$, where $s_k = [a_k; a_{k+1}, a_{k+2}, \dots]$. On the other hand, from the convergent recurrence we derive that -$$\vec r_k = \vec r_{k-2} + \left\lfloor \left| \frac{\vec r \times \vec r_{k-2}}{\vec r \times \vec r_{k-1}}\right|\right\rfloor \cdot \vec r_{k-1}.$$ + $$r = [a_0; a_1, \dots, a_{k-1}, s_k] = \frac{s_k p_{k-1} + p_{k-2}}{s_k q_{k-1} + q_{k-2}}.$$ -Note that $\vec r_{k-1}$ and $\vec r_{k-2}$ generally lie on different sides of $\vec r$, thus $\vec r \times \vec r_{k-2}$ and $\vec r \times \vec r_{k-1}$ have different signs. + In vector form, it rewrites as -### Nose stretching + $$\vec r \parallel s_k \vec r_{k-1} + \vec r_{k-2},$$ -Geometrically, $a_k=\lfloor s_k \rfloor$ in the expression above is equal to the maximum integer number of $\vec r_{k-1}$ vectors that can be added to $\vec r_{k-2}$ in such a way that the resulting vector will still be on the same side from $\vec r$ as $\vec r_{k-2}$ is. + meaning that $\vec r$ and $s_k \vec r_{k-1} + \vec r_{k-2}$ are collinear (that is, have the same slope coefficient). Taking the [pseudoscalar product](../geometry/basic-geometry.md) of both parts with $\vec r$, we get -![](https://upload.wikimedia.org/wikipedia/commons/9/92/Continued_convergents_geometry.svg) + $$0 = s_k (\vec r_{k-1} \times \vec r) + (\vec r_{k-2} \times \vec r),$$ -On the picture above you can see how $\vec r_2 = (4,3)$ is obtained by repeatedly adding $\vec r_1 = (1,1)$ to $\vec r_0 = (1, 0)$. When it is not possible to further add $\vec r_1$ to $\vec r_0$ without crossing the $y=rx$ line, we go to the other side and repeatedly add $\vec r_2$ to $\vec r_1$ to obtain $\vec r_3 = (9, 7)$ in a similar manner. + which yields the final formula -This procedure generates exponentially longer vectors, that approach closer and closer to $y=rx$ line, until one vector is finally collinear with it (when $r$ is rational). For this property, the procedure of generating consequent convergent vectors was dubbed the nose stretching algorithm by Boris Delaunay. + $$s_k = -\frac{\vec r_{k-2} \times \vec r}{\vec r_{k-1} \times \vec r}.$$ -### Klein polygons +!!! example "Nose stretching" + Each time you add $\vec r_{k-1}$ to the vector $\vec p$, the value of $\vec p \times \vec r$ is increased by $\vec r_{k-1} \times \vec r$. -If we look on the triangle drawn on points $\vec r_{k-2}$, $\vec r_{k}$ and $\vec 0$ we will notice that its doubled area is + Thus, $a_k=\lfloor s_k \rfloor$ is the maximum integer number of $\vec r_{k-1}$ vectors that can be added to $\vec r_{k-2}$ without changing the sign of the cross product with $\vec r$. -$$|\vec r_{k-2} \times \vec r_k| = a_k.$$ + In other words, $a_k$ is the maximum integer number of times you can add $\vec r_{k-1}$ to $\vec r_{k-2}$ without crossing the line defined by $\vec r$: -Combined with the [Pick's theorem](../geometry/picks-theorem.md), it means that there are no lattice points strictly inside the triangle and the only lattice points on its border are $\vec 0$ and $\vec r_{k-2} + t \cdot \vec r_{k-1}$ for all integer $t$ such that $0 \leq t \leq a_k$. When joined for all possible $k$ it means that there are no integer points in the space between polygons formed by even-indexed and odd-indexed convergent vectors. + ![](https://upload.wikimedia.org/wikipedia/commons/9/92/Continued_convergents_geometry.svg) -This, in turn, means that $\vec r_k$ with odd coefficients form a convex hull of lattice points with $x \geq 0$ above the line $y=rx$, while $\vec r_k$ with even coefficients form a convex hull of lattice points with $x > 0$ below the line $y=rx$. + On the picture above, $\vec r_2 = (4;3)$ is obtained by repeatedly adding $\vec r_1 = (1;1)$ to $\vec r_0 = (1;0)$. + When it is not possible to further add $\vec r_1$ to $\vec r_0$ without crossing the $y=rx$ line, we go to the other side and repeatedly add $\vec r_2$ to $\vec r_1$ to obtain $\vec r_3 = (9;7)$. -!!! abstract "Definition" + This procedure generates exponentially longer vectors, that approach the line. - These polygons are also known as **Klein polygons**, named after Felix Klein who first suggested this geometric interpretation to the continued fractions. + For this property, the procedure of generating consequent convergent vectors was dubbed the **nose stretching algorithm** by Boris Delaunay. +!!! note "Klein polygons" -!!! abstract "Definition" + If we look on the triangle drawn on points $\vec r_{k-2}$, $\vec r_{k}$ and $\vec 0$ we will notice that its doubled area is + + $$|\vec r_{k-2} \times \vec r_k| = |\vec r_{k-2} \times (\vec r_{k-2} + a_k \vec r_{k-1})| = a_k |\vec r_{k-2} \times \vec r_{k-1}| = a_k.$$ - The vectors $\vec r_{k-2} + t \cdot \vec r_{k-1}$ for $0 \leq t \leq a_k$ and corresponding fractions are called the **semiconvergents**. + Combined with the [Pick's theorem](../geometry/picks-theorem.md), it means that there are no lattice points strictly inside the triangle and the only lattice points on its border are $\vec 0$ and $\vec r_{k-2} + t \cdot \vec r_{k-1}$ for all integer $t$ such that $0 \leq t \leq a_k$. When joined for all possible $k$ it means that there are no integer points in the space between polygons formed by even-indexed and odd-indexed convergent vectors. -Semiconvergent vectors are essentially _all_ lattice vectors on the border of their corresponding convex hulls. + This, in turn, means that $\vec r_k$ with odd coefficients form a convex hull of lattice points with $x \geq 0$ above the line $y=rx$, while $\vec r_k$ with even coefficients form a convex hull of lattice points with $x > 0$ below the line $y=rx$. + + +!!! abstract "Definition" + + These polygons are also known as **Klein polygons**, named after Felix Klein who first suggested this geometric interpretation to the continued fractions. ## Problem examples From 1d140438da82dae0384ce7800ee32004fe3e68e5 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Wed, 30 Mar 2022 03:08:40 +0200 Subject: [PATCH 34/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 87 +++++++++++++++++++++++++++--- 1 file changed, 81 insertions(+), 6 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 3c4d25e03..4ae1a5511 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -61,7 +61,7 @@ Besides that, continued fractions are closely related to Euclidean algorithm whi !!! abstract "Definition" - Let $r_k = [a_0; a_1, \dots, a_k]$. The numbers $[a_0; a_1, \dots, t]$ for $1 \leq t \leq a_k$ are called **semiconvergents**. + Let $r_k = [a_0; a_1, \dots, a_{k-1}, a_k]$. The numbers $[a_0; a_1, \dots, a_{k-1}, t]$ for $1 \leq t \leq a_k$ are called **semiconvergents**. !!! abstract "Definition" Complementary to convergents, we define the **residues** as $s_k = [a_k; a_{k+1}, a_{k+2}, \dots]$. Correspondingly, we will call an individual $s_k$ the $k$-th residue of $r$. @@ -418,14 +418,92 @@ _You can mostly skip this section if you're more interested in practical results Now that the most important facts and concepts were introduced, it is time to delve into specific problem examples. -!!! example "[Timus - Crime and Punishment](https://acm.timus.ru/problem.aspx?space=1&num=1430)" +!!! example "Convex hull under the line" + Find the convex hull of lattice points $(x;y)$ such that $0 \leq x \leq N$ and $0 \leq y \leq rx$ for $r=[a_0;a_1,\dots,a_k]=\frac{p_k}{q_k}$. + +!!! hint "Solution" + If we were considering the unbounded set $0 \leq x$, the upper convex hull would be given by the line $y=rx$ itself. + + However, with additional constraint $x \leq N$ we'd need to eventually deviate from the line to maintain proper convex hull. + + Let $t = \lfloor \frac{N}{q_k}\rfloor$, then first $t$ lattice points on the hull after $(0;0)$ are $\alpha \cdot (q_k; p_k)$ for integer $1 \leq \alpha \leq t$. + + However $(t+1)(q_k; p_k)$ can't be next lattice point since $(t+1)q_k$ is greater than $N$. + + To get to the next lattice points in the hull, we should get to the point $(x;y)$ which diverges from $y=rx$ by the smallest margin, while maintaining $x \leq N$. + + Let $(x; y)$ be the last current point in the convex hull. Then the next point $(x'; y')$ is such that $x' \leq N$ and $(x'; y') - (x; y) = (\Delta x; \Delta y)$ is as close to the line $y=rx$ as possible. In other words, $(\Delta x; \Delta y)$ maximizes $r \Delta x - \Delta y$ subject to $\Delta x \leq N - x$ and $\Delta y \leq r \Delta x$. + + Points like that lie on the convex hull of lattice points below $y=rx$. In other words, $(\Delta x; \Delta y)$ must be a lower semiconvergent of $r$. + + That being said, $(\Delta x; \Delta y)$ is of form $(q_{i-1}; p_{i-1}) + t \cdot (q_i; p_i)$ for some odd number $i$ and $0 \leq t < a_i$. + + To find such $i$, we can traverse all possible $i$ starting from the largest one and use $t = \lfloor \frac{N-x-q_{i-1}}{q_i} \rfloor$ for $i$ such that $N-x-q_{i-1} \geq 0$. + + With $(\Delta x; \Delta y) = (q_{i-1}; p_{i-1}) + t \cdot (q_i; p_i)$, the condition $\Delta y \leq r \Delta x$ would be preserved by semiconvergent properties. + + And $t < a_i$ would hold because we already exhausted semiconvergents obtained from $i+2$, hence $x + q_{i-1} + a_i q_i = x+q_{i+1}$ is greater than $N$. + + Now that we know $(\Delta x; \Delta y)$, we may add it to $(x;y)$ for $k = \lfloor \frac{N-x}{\Delta x} \rfloor$ times before we exceed $N$, after which we would try the next semiconvergent. + === "C++" + ```cpp + // returns [ah, ph, qh] such that points r[i]=(ph[i], qh[i]) constitute upper convex hull + // of lattice points on 0 <= x <= N and 0 <= y <= r * x, where r = [a0; a1, a2, ...] + // and there are ah[i]-1 integer points on the segment between r[i] and r[i+1] + auto hull(auto a, int N) { + auto [p, q] = convergents(a); + int t = N / q.back(); + vector ah = {t}; + vector ph = {0, t*p.back()}; + vector qh = {0, t*q.back()}; + + for(int i = q.size() - 1; i >= 0; i--) { + if(i % 2) { + while(qh.back() + q[i - 1] <= N) { + t = (N - qh.back() - q[i - 1]) / q[i]; + int dp = p[i - 1] + t * p[i]; + int dq = q[i - 1] + t * q[i]; + int k = (N - qh.back()) / dq; + ah.push_back(k); + ph.push_back(ph.back() + k * dp); + qh.push_back(qh.back() + k * dq); + } + } + } + return make_tuple(ah, ph, qh); + } + ``` + === "Python" + ```py + # returns [ah, ph, qh] such that points r[i]=(ph[i], qh[i]) constitute upper convex hull + # of lattice points on 0 <= x <= N and 0 <= y <= r * x, where r = [a0; a1, a2, ...] + # and there are ah[i]-1 integer points on the segment between r[i] and r[i+1] + def hull(a, N): + p, q = convergents(a) + t = N // q[-1] + ah = [t] + ph = [0, t*p[-1]] + qh = [0, t*q[-1]] + for i in reversed(range(len(q))): + if i % 2 == 1: + while qh[-1] + q[i-1] <= N: + t = (N - qh[-1] - q[i-1]) // q[i] + dp = p[i-1] + t*p[i] + dq = q[i-1] + t*q[i] + k = (N - qh[-1]) // dq + ah.append(k) + ph.append(ph[-1] + k * dp) + qh.append(qh[-1] + k * dq) + return ah, ph, qh + ``` + +!!! example "[Timus - Crime and Punishment](https://acm.timus.ru/problem.aspx?space=1&num=1430)" You're given integer numbers $A$, $B$ and $N$. Find $x \geq 0$ and $y \geq 0$ such that $Ax + By \leq N$ and $Ax + By$ is the maximum possible. _Equivalent formulation:_ Given $A$, $B$, $C$ and $N$, find $x$ such that $0 \leq x \leq N$ and $\lfloor \frac{Ax+B}{C} \rfloor$ is the maximum possible. ??? hint "Solution" - In the actual problem it holds that $1 \leq A, B, N \leq 2 \cdot 10^9$, so the problem can be solved in $O(\sqrt N)$. However, there is $O(\log N)$ solution with continued fractions. @@ -450,18 +528,15 @@ Now that the most important facts and concepts were introduced, it is time to de ``` !!! example "[CodeChef - Euler Sum](https://www.codechef.com/problems/ES)" - Compute $\sum\limits_{x=1}^N \lfloor ex \rfloor$, where $e = [2; 1, 2, 1, 1, 4, 1, 1, 6, 1, \dots, 1, 2n, 1, \dots]$ is the Euler's number and $N \leq 10^{4000}$. !!! example "[Kattis - It's a Mod, Mod, Mod, Mod World](https://open.kattis.com/problems/itsamodmodmodmodworld)" - Given $p$, $q$ and $n$, compute $\sum\limits_{i=1}^n [p \cdot i \bmod q]$. The connection between $\bmod$ and $\lfloor \cdot \rfloor$ is given as $a \bmod b = a - \lfloor \frac{a}{b} \rfloor b$. !!! example "[Library Checker - Sum of Floor of Linear](https://judge.yosupo.jp/problem/sum_of_floor_of_linear)" - Given $N$, $M$, $A$ and $B$, compute $\sum\limits_{i=0}^{N-1} \lfloor \frac{A \cdot i + B}{M} \rfloor$. This one is a bit more tricky. We'll discuss possible approaches to tackle it further below. From 80a1e966b6660766f2d4c970fde48e5a36f6c876 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Wed, 30 Mar 2022 20:03:34 +0200 Subject: [PATCH 35/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 35 ++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 4ae1a5511..2f318e134 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -205,6 +205,8 @@ Convergents are the core concept of continued fractions, so it is important to s Thus, $r_k$ is a weighted [mediant](https://en.wikipedia.org/wiki/Mediant_(mathematics)) of $r_{k-1}$ and $r_{k-2}$. + Note that if $\gcd(a,b)=\gcd(c,d)=1$ then $\gcd(a+c,b+d)=1$ as well, hence for all convergents $r_k = \frac{p_k}{q_k}$, it holds that $\gcd(p_k, q_k)=1$. + ??? hint "Detailed explanation" The numerator and the denominator of $r_k$ can be seen as multivariate polynomials of $a_0, a_1, \dots, a_k$: @@ -249,6 +251,39 @@ Convergents are the core concept of continued fractions, so it is important to s $$P_k(a_0, \dots, a_k) = a_k P_{k-1}(a_0, \dots, a_{k-1}) + P_{k-2}(a_0, \dots, a_{k-2}).$$ +!!! note "Connection with the Stern-Brocot tree" + [The Stern-Brocot tree](../others/stern_brocot_tree_farey_sequences.md) is a binary search tree that contains all the distinct positive rational numbers. + + The tree generally looks as follows: + +
![](https://upload.wikimedia.org/wikipedia/commons/3/37/SternBrocotTree.svg) +
_[The image](https://commons.wikimedia.org/wiki/File:SternBrocotTree.svg) by [Aaron Rotenberg](https://commons.wikimedia.org/wiki/User:Aaron_Rotenberg) is licensed under [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/deed.en)_
+ + Fractions $\frac{0}{1}$ and $\frac{1}{0}$ are "virtually" kept on the left and right sides of the tree correspondingly. + + Then the fraction in a node is a mediant $\frac{a+c}{b+d}$ of two fractions $\frac{a}{b}$ and $\frac{c}{d}$ above it. + + From the $\frac{p_k}{q_k}=\frac{a_k p_{k-1} + p_{k-2}}{a_k q_{k-1} + q_{k-2}}$ recurrence we see that the continued fraction representation encodes the path to the fraction $\frac{p_k}{q_k}$ in the Stern-Brocot tree. + + To find $[a_0; a_1, \dots, a_{k}, 1]$ in a tree, one needs to move $a_0$ times to the right, $a_1$ times to the left, $a_2$ times to the right and so on, ignoring the last $1$. + + From this follows that the parent of $[a_0; a_1, \dots, a_k,1]$ is obtained by taking one step back in the last used direction. + + In other words, it is $[a_0; a_1, \dots, a_k-1,1]$ when $a_k > 1$ and $[a_0; a_1, \dots, a_{k-1}, 1]$ when $a_k = 1$. + + On the other hand, this also allows to derive that the children of $[a_0; a_1, \dots, a_k, 1]$ are $[a_0; a_1, \dots, a_k+1, 1]$ and $[a_0; a_1, \dots, a_k, 1, 1]$. + + There is an indexing of Stern-Brocot vertices that is consistent with this structure. Let's assign the root vertex an index $1$. Then for a vertex number $v$, index of its left child is obtained by changing leading bit of $v$ from $1$ to $10$ and for the right child, it's obtained by changing leading bit of $v$ from $1$ to $11$: + +
+ + In this indexing, the continued fraction representation of a rational number specifies the [run-length encoding](https://en.wikipedia.org/wiki/Run-length_encoding) of its binary index. + + For example, for $\frac{5}{2} = [2;2] = [2;1,1]$, its index is $1011_2$ and run-length encoding of it, if bits are considered in ascending order, is exactly $[2;1,1]$. + + Another example is $\frac{2}{5} = [0;2,2]=[0;2,1,1]$, which has index $1100_2$ and its run-length encoding is, indeed, $[0;2,2]$. + + ### Implementation We will compute the convergents as a pair of sequences $p_{-2}, p_{-1}, p_0, p_1, \dots, p_k$ and $q_{-2}, q_{-1}, q_0, q_1, \dots, q_k$: From 6f237e035ec24f1ef723208588f5f47616dd4471 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Wed, 30 Mar 2022 20:06:15 +0200 Subject: [PATCH 36/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 2f318e134..8eb21c9c8 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -1,5 +1,5 @@ -# Continued fractions in competitive programming +# Continued fractions **Continued fraction** is a representation of a real number as a specific convergent sequence of rational numbers. They are useful in competitive programming because they are easy to compute and can be efficiently used to find the best possible rational approximation of the underlying real number (among all numbers whose denominator doesn't exceed a given value). From db758804bb274e7c839e13253c86779ff2d14401 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Wed, 30 Mar 2022 21:26:31 +0200 Subject: [PATCH 37/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 89 +++++++++++++++++++++--------- 1 file changed, 62 insertions(+), 27 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 8eb21c9c8..21b5422e1 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -251,8 +251,41 @@ Convergents are the core concept of continued fractions, so it is important to s $$P_k(a_0, \dots, a_k) = a_k P_{k-1}(a_0, \dots, a_{k-1}) + P_{k-2}(a_0, \dots, a_{k-2}).$$ -!!! note "Connection with the Stern-Brocot tree" - [The Stern-Brocot tree](../others/stern_brocot_tree_farey_sequences.md) is a binary search tree that contains all the distinct positive rational numbers. +### Implementation + +We will compute the convergents as a pair of sequences $p_{-2}, p_{-1}, p_0, p_1, \dots, p_k$ and $q_{-2}, q_{-1}, q_0, q_1, \dots, q_k$: + +=== "C++" + ```cpp + auto convergents(vector a) { + vector p = {0, 1}; + vector q = {1, 0}; + for(auto it: a) { + p.push_back(p[p.size() - 1] * it + p[p.size() - 2]); + q.push_back(q[q.size() - 1] * it + q[q.size() - 2]); + } + return make_pair(p, q); + } + ``` +=== "Python" + ```py + def convergents(a): + p = [0, 1] + q = [1, 0] + for it in a: + p.append(p[-1]*it + p[-2]) + q.append(q[-1]*it + q[-2]) + return p, q + ``` + +## Organizing continued fractions in trees + +There are two major ways to unite all possible continued fractions into useful tree structures. + +The Stern-Brocot tree is particularly useful because it allows to do a binary search on all rational numbers and the result would converge as fast as convergents of continued fractions do. + +!!! note "Connection with the Stern–Brocot tree" + [The Stern-Brocot tree](../others/stern_brocot_tree_farey_sequences.md) is a binary search tree that contains all distinct positive rational numbers. The tree generally looks as follows: @@ -283,34 +316,36 @@ Convergents are the core concept of continued fractions, so it is important to s Another example is $\frac{2}{5} = [0;2,2]=[0;2,1,1]$, which has index $1100_2$ and its run-length encoding is, indeed, $[0;2,2]$. - -### Implementation +Another, somewhat simpler way to organize continued fractions in a binary tree is the Calkin-Wilf tree. Unfortunately, unlike the Stern-Brocot tree, Calkin-Wif tree is not a binary _search_ tree, so it can't be used to emulate rational binary search. -We will compute the convergents as a pair of sequences $p_{-2}, p_{-1}, p_0, p_1, \dots, p_k$ and $q_{-2}, q_{-1}, q_0, q_1, \dots, q_k$: +!!! note "Connection with the Calkin–Wilf tree" + [The Calkin-Wilf tree](https://en.wikipedia.org/wiki/Calkin–Wilf_tree) is another binary tree which contains all distinct positive rational numbers. -=== "C++" - ```cpp - auto convergents(vector a) { - vector p = {0, 1}; - vector q = {1, 0}; - for(auto it: a) { - p.push_back(p[p.size() - 1] * it + p[p.size() - 2]); - q.push_back(q[q.size() - 1] * it + q[q.size() - 2]); - } - return make_pair(p, q); - } - ``` -=== "Python" - ```py - def convergents(a): - p = [0, 1] - q = [1, 0] - for it in a: - p.append(p[-1]*it + p[-2]) - q.append(q[-1]*it + q[-2]) - return p, q - ``` + The tree generally looks like this: + +
+
[The image](https://commons.wikimedia.org/wiki/File:Calkin–Wilf_tree.svg) by [Olli Niemitalo](https://commons.wikimedia.org/wiki/User:Olli_Niemitalo), [Proz](https://commons.wikimedia.org/wiki/User:Proz) is licensed under [CC0 1.0](https://creativecommons.org/publicdomain/zero/1.0/deed.en)
+ + In the root of the tree, the number $\frac{1}{1}$ is located. Then, for the vertex with a number $\frac{p}{q}$, its children are $\frac{p}{p+q}$ and $\frac{p+q}{q}$. + + In the Calkin-Wilf tree, for the fraction $\frac{p}{q}$, its direct parent is $\frac{p-q}{q}$ when $p>q$ and $\frac{p}{q-p}$ otherwise. + + For the Stern-Brocot tree, we used the recurrence for convergents. To draw the connection between the continued fraction and the Calkin-Wilf tree, we should recall the recurrence for residues. If $s_k = \frac{p}{q}$, then $s_{k+1} = \frac{q}{p \mod q} = \frac{q}{p-\lfloor p/q \rfloor \cdot q}$. + + On the other hand, if we repeatedly go from $s_k = \frac{p}{q}$ to its parent in the Calkin-Wilf tree when $p > q$, we will end up in $\frac{p \mod q}{q} = \frac{1}{s_{k+1}}$. If we continue doing so, we will end up in $s_{k+2}$, then $\frac{1}{s_{k+3}}$ and so on. From this we can deduce that: + + 1. When $a_0> 0$, the direct parent of $[a_0; a_1, \dots, a_k]$ in the Calkin-Wilf tree is $\frac{p-q}{q}=[a_0 - 1; a_1, \dots, a_k]$. + 2. When $a_0 = 0$ and $a_1 > 1$, its direct parent is $\frac{p}{q-p} = [0; a_1 - 1, a_2, \dots, a_k]$. + 3. And when $a_0 = 0$ and $a_1 = 1$, its direct parent is $\frac{p}{q-p} = [a_2; a_3, \dots, a_k]$. + + Correspondingly, children of $\frac{p}{q} = [a_0; a_1, \dots, a_k]$ are + + 1. $\frac{p+q}{q}=[a_0+1; a_1, \dots, a_k]$, + 2. $\frac{p}{p+q} = [0, 1, a_0, a_1, \dots, a_k]$ (when $a_0 > 0$) or $\frac{p}{p+q} = [0, a_1+1, a_2, \dots, a_k]$ (when $a_0=0$). + + Noteworthy, if we enumerate vertices of the Calkin-Wilf tree in the breadth-first search order (that is, the root has a number $1$, and the children of the vertex $v$ have indices $2v$ and $2v+1$ correspondingly), the index of the rational number in the Calkin-Wilf tree would be the same as in the Stern-Brocot tree. + Thus, numbers on the same levels of the Stern-Brocot tree and the Calkin-Wilf tree are the same, but their ordering differs through the [bit-reversal permutation](https://en.wikipedia.org/wiki/Bit-reversal_permutation). ## Convergence _You can mostly skip this section if you're more interested in practical results._ From 2c43fe3361a6b39ef917dbe1db66271bc9f2e2ab Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Wed, 30 Mar 2022 21:33:39 +0200 Subject: [PATCH 38/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 21b5422e1..0c6950fed 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -340,8 +340,8 @@ Another, somewhat simpler way to organize continued fractions in a binary tree i Correspondingly, children of $\frac{p}{q} = [a_0; a_1, \dots, a_k]$ are - 1. $\frac{p+q}{q}=[a_0+1; a_1, \dots, a_k]$, - 2. $\frac{p}{p+q} = [0, 1, a_0, a_1, \dots, a_k]$ (when $a_0 > 0$) or $\frac{p}{p+q} = [0, a_1+1, a_2, \dots, a_k]$ (when $a_0=0$). + 1. $\frac{p+q}{q}=1+\frac{p}{q}$, which is $[a_0+1; a_1, \dots, a_k]$, + 2. $\frac{p}{p+q} = \frac{1}{1+\frac{q}{p}}$, which is $[0, 1, a_0, a_1, \dots, a_k]$ for $a_0 > 0$ and $[0, a_1+1, a_2, \dots, a_k]$ for $a_0=0$. Noteworthy, if we enumerate vertices of the Calkin-Wilf tree in the breadth-first search order (that is, the root has a number $1$, and the children of the vertex $v$ have indices $2v$ and $2v+1$ correspondingly), the index of the rational number in the Calkin-Wilf tree would be the same as in the Stern-Brocot tree. From 8dee6965a133fd54468ca1259113d2580af42457 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Wed, 30 Mar 2022 21:39:18 +0200 Subject: [PATCH 39/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 0c6950fed..d3ff25675 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -41,6 +41,11 @@ Besides that, continued fractions are closely related to Euclidean algorithm whi is called the **continued fraction representation** of the irrational number $r$ and is denoted shortly as $r = [a_0;a_1,a_2,\dots]$. +!!! note "Basic arithmetics" + Note that for $r=[a_0;a_1,\dots]$ and integer $k$, it holds that $r+k = [a_0+k; a_1, \dots]$. + + Another important observation that $\frac{1}{r}=[0;a_0, a_1, \dots]$ when $a_0 \neq 0$ and $\frac{1}{r} = [a_1; a_2, \dots]$ when $a_0 = 0$. + !!! abstract "Definition" In the definition above, rational numbers $r_0, r_1, r_2, \dots$ are called the **convergents** of $r$. From 161cbd4ede8027090133ffe7c997782f50065c1e Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Wed, 30 Mar 2022 23:17:10 +0200 Subject: [PATCH 40/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index d3ff25675..207c3b6ec 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -49,7 +49,7 @@ Besides that, continued fractions are closely related to Euclidean algorithm whi !!! abstract "Definition" In the definition above, rational numbers $r_0, r_1, r_2, \dots$ are called the **convergents** of $r$. - Correspondingly, individual $r_k = [a_0; a_1, \dots, a_k]$ is called the $k$-th **convergent** of $r$. + Correspondingly, individual $r_k = [a_0; a_1, \dots, a_k] = \frac{p_k}{q_k}$ is called the $k$-th **convergent** of $r$. ??? example Consider $r = [1; 1, 1, 1, \dots]$. It can be proven by induction that $r_k = \frac{F_{k+2}}{F_{k+1}}$, where $F_k$ is the Fibonacci sequence defined as $F_0 = 0$, $F_1 = 1$ and $F_{k} = F_{k-1} + F_{k-2}$. From the Binet's formula, it is known that @@ -68,6 +68,8 @@ Besides that, continued fractions are closely related to Euclidean algorithm whi !!! abstract "Definition" Let $r_k = [a_0; a_1, \dots, a_{k-1}, a_k]$. The numbers $[a_0; a_1, \dots, a_{k-1}, t]$ for $1 \leq t \leq a_k$ are called **semiconvergents**. + We will typically refer to (semi)convergents that are greater than $r$ as **upper** (semi)convergents and to those that are less than $r$ as **lower** (semi)convergents. + !!! abstract "Definition" Complementary to convergents, we define the **residues** as $s_k = [a_k; a_{k+1}, a_{k+2}, \dots]$. Correspondingly, we will call an individual $s_k$ the $k$-th residue of $r$. @@ -210,6 +212,8 @@ Convergents are the core concept of continued fractions, so it is important to s Thus, $r_k$ is a weighted [mediant](https://en.wikipedia.org/wiki/Mediant_(mathematics)) of $r_{k-1}$ and $r_{k-2}$. + For consistency, two additional convergents $r_{-1} = \frac{1}{0}$ and $r_{-2} = \frac{0}{1}$ are defined. + Note that if $\gcd(a,b)=\gcd(c,d)=1$ then $\gcd(a+c,b+d)=1$ as well, hence for all convergents $r_k = \frac{p_k}{q_k}$, it holds that $\gcd(p_k, q_k)=1$. ??? hint "Detailed explanation" @@ -321,7 +325,7 @@ The Stern-Brocot tree is particularly useful because it allows to do a binary se Another example is $\frac{2}{5} = [0;2,2]=[0;2,1,1]$, which has index $1100_2$ and its run-length encoding is, indeed, $[0;2,2]$. -Another, somewhat simpler way to organize continued fractions in a binary tree is the Calkin-Wilf tree. Unfortunately, unlike the Stern-Brocot tree, Calkin-Wif tree is not a binary _search_ tree, so it can't be used to emulate rational binary search. +Another, somewhat simpler way to organize continued fractions in a binary tree is the Calkin-Wilf tree. Unfortunately, unlike the Stern-Brocot tree, Calkin-Wilf tree is not a binary _search_ tree, so it can't be used to emulate rational binary search. !!! note "Connection with the Calkin–Wilf tree" [The Calkin-Wilf tree](https://en.wikipedia.org/wiki/Calkin–Wilf_tree) is another binary tree which contains all distinct positive rational numbers. @@ -404,9 +408,10 @@ _You can mostly skip this section if you're more interested in practical results $$r-r_k = \sum\limits_{i=k+1}^\infty \frac{(-1)^{i-1}}{q_i q_{i-1}}$$ - has the same sign as $(-1)^k$ due to how fast $q_i q_{i-1}$ decreases. It means that even-indexed $r_k$ monotonously approach $r$ from below while odd-indexed $r_k$ monotonously approach it from above: + has the same sign as $(-1)^k$ due to how fast $q_i q_{i-1}$ decreases. Hence even-indexed $r_k$ approach $r$ from below while odd-indexed $r_k$ approach it from above: - ![](https://upload.wikimedia.org/wikipedia/commons/b/b4/Golden_ration_convergents.svg) +
+
_Convergents of $r=\phi = \frac{1+\sqrt{5}}{2}=[1;1,1,\dots]$ and their distance from $r$._
From this picture we can see that @@ -457,14 +462,15 @@ _You can mostly skip this section if you're more interested in practical results $$s_k = -\frac{\vec r_{k-2} \times \vec r}{\vec r_{k-1} \times \vec r}.$$ -!!! example "Nose stretching" +!!! example "Nose stretching algorithm" Each time you add $\vec r_{k-1}$ to the vector $\vec p$, the value of $\vec p \times \vec r$ is increased by $\vec r_{k-1} \times \vec r$. Thus, $a_k=\lfloor s_k \rfloor$ is the maximum integer number of $\vec r_{k-1}$ vectors that can be added to $\vec r_{k-2}$ without changing the sign of the cross product with $\vec r$. In other words, $a_k$ is the maximum integer number of times you can add $\vec r_{k-1}$ to $\vec r_{k-2}$ without crossing the line defined by $\vec r$: - ![](https://upload.wikimedia.org/wikipedia/commons/9/92/Continued_convergents_geometry.svg) +
+
_Convergents of $r=\frac{7}{9}=[0;1,3,2]$. Semiconvergents correspond to intermediate points between gray arrows._
On the picture above, $\vec r_2 = (4;3)$ is obtained by repeatedly adding $\vec r_1 = (1;1)$ to $\vec r_0 = (1;0)$. @@ -507,6 +513,9 @@ Now that the most important facts and concepts were introduced, it is time to de To get to the next lattice points in the hull, we should get to the point $(x;y)$ which diverges from $y=rx$ by the smallest margin, while maintaining $x \leq N$. +
+
Convex hull of lattice points under $y=\frac{4}{7}x$ for $0 \leq x \leq 19$ consists of points $(0;0), (7;4), (14;8), (16;9), (18;10), (19;10)$.
+ Let $(x; y)$ be the last current point in the convex hull. Then the next point $(x'; y')$ is such that $x' \leq N$ and $(x'; y') - (x; y) = (\Delta x; \Delta y)$ is as close to the line $y=rx$ as possible. In other words, $(\Delta x; \Delta y)$ maximizes $r \Delta x - \Delta y$ subject to $\Delta x \leq N - x$ and $\Delta y \leq r \Delta x$. Points like that lie on the convex hull of lattice points below $y=rx$. In other words, $(\Delta x; \Delta y)$ must be a lower semiconvergent of $r$. @@ -519,7 +528,7 @@ Now that the most important facts and concepts were introduced, it is time to de And $t < a_i$ would hold because we already exhausted semiconvergents obtained from $i+2$, hence $x + q_{i-1} + a_i q_i = x+q_{i+1}$ is greater than $N$. - Now that we know $(\Delta x; \Delta y)$, we may add it to $(x;y)$ for $k = \lfloor \frac{N-x}{\Delta x} \rfloor$ times before we exceed $N$, after which we would try the next semiconvergent. + Now that we may add $(\Delta x; \Delta y)$, to $(x;y)$ for $k = \lfloor \frac{N-x}{\Delta x} \rfloor$ times before we exceed $N$, after which we would try the next semiconvergent. === "C++" ```cpp From b9fc498c1eddaecb3ab7f82ac807b68ba3e6fafd Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Wed, 30 Mar 2022 23:22:16 +0200 Subject: [PATCH 41/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 207c3b6ec..680ad381e 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -502,7 +502,7 @@ Now that the most important facts and concepts were introduced, it is time to de !!! example "Convex hull under the line" Find the convex hull of lattice points $(x;y)$ such that $0 \leq x \leq N$ and $0 \leq y \leq rx$ for $r=[a_0;a_1,\dots,a_k]=\frac{p_k}{q_k}$. -!!! hint "Solution" +??? hint "Solution" If we were considering the unbounded set $0 \leq x$, the upper convex hull would be given by the line $y=rx$ itself. However, with additional constraint $x \leq N$ we'd need to eventually deviate from the line to maintain proper convex hull. @@ -594,7 +594,7 @@ Now that the most important facts and concepts were introduced, it is time to de It is evident that one needs to find the maximum value of $\lfloor \frac{N-Ax}{B} \rfloor$ for $0 \leq x \leq \lfloor \frac{N}{A}\rfloor$. - For our convenience, we will invert the direction of $x$, so that now we need to find the maximum value of $\lfloor \frac{Ax + \left(N \bmod A \right)}{B} \rfloor$ for $0 \leq x \leq \lfloor \frac{N}{A} \rfloor$. + For our convenience, we will invert the direction of $x$, so that now we need to find the maximum value of $\lfloor \frac{Ax + \left(N \mod A \right)}{B} \rfloor$ for $0 \leq x \leq \lfloor \frac{N}{A} \rfloor$. To treat it more generically, we will write a function that finds the maximum value of $\lfloor \frac{Ax+B}{C} \rfloor$ on $0 \leq x \leq N$: From dc774f9191393ede12dba245ac5d49d1aace4fa0 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Thu, 31 Mar 2022 04:20:16 +0200 Subject: [PATCH 42/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 220 +++++++++++++++++++++++++++-- 1 file changed, 206 insertions(+), 14 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index 680ad381e..e2a2e2ace 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -582,7 +582,7 @@ Now that the most important facts and concepts were introduced, it is time to de return ah, ph, qh ``` -!!! example "[Timus - Crime and Punishment](https://acm.timus.ru/problem.aspx?space=1&num=1430)" +!!! example "[Timus - Crime and Punishment](https://timus.online/problem.aspx?space=1&num=1430)" You're given integer numbers $A$, $B$ and $N$. Find $x \geq 0$ and $y \geq 0$ such that $Ax + By \leq N$ and $Ax + By$ is the maximum possible. _Equivalent formulation:_ Given $A$, $B$, $C$ and $N$, find $x$ such that $0 \leq x \leq N$ and $\lfloor \frac{Ax+B}{C} \rfloor$ is the maximum possible. @@ -594,33 +594,225 @@ Now that the most important facts and concepts were introduced, it is time to de It is evident that one needs to find the maximum value of $\lfloor \frac{N-Ax}{B} \rfloor$ for $0 \leq x \leq \lfloor \frac{N}{A}\rfloor$. - For our convenience, we will invert the direction of $x$, so that now we need to find the maximum value of $\lfloor \frac{Ax + \left(N \mod A \right)}{B} \rfloor$ for $0 \leq x \leq \lfloor \frac{N}{A} \rfloor$. + For our convenience, we will invert the direction of $x$, so that now we need to find the maximum value of $\lfloor \frac{Ax + \left(N \;\bmod\; A \right)}{B} \rfloor$ for $0 \leq x \leq \lfloor \frac{N}{A} \rfloor$. - To treat it more generically, we will write a function that finds the maximum value of $\lfloor \frac{Ax+B}{C} \rfloor$ on $0 \leq x \leq N$: + To treat it more generically, we will write a function that finds the maximum value of $\lfloor \frac{Ax+B}{C} \rfloor$ on $0 \leq x \leq N$. + + Core solution idea in this problem essentially repeats the previous problem, but instead of using lower semiconvergents to diverge from line, you use upper semiconvergents to get closer to the line without crossing it and without violating $x \leq N$. Unfortunately, unlike the previous problem, you need to make sure that you don't cross the $y=\frac{Ax+B}{C}$ line while getting closer to it, so you should keep it in mind when calculating semiconvergent's coefficient $t$. - === "C++" - ```cpp - auto solve(int A, int B, int N) { - return max_floor(A, N % A, B, N / A); - } - ``` === "Python" ```py + # (x, y) such that y = (A*x+B)//C, + # y mod C is max + # and 0 <= x <= N. + def max_floor(A, B, C, N): + # y <= (A*x + B)/C <=> diff(x, y) <= B + def diff(x, y): + return C*y-A*x + a = fraction(A, C) + p, q = convergents(a) + ph = [B // C] + qh = [0] + for i in range(2, len(q) - 1): + if i % 2 == 0: + while diff(qh[-1] + q[i+1], ph[-1] + p[i+1]) <= B: + t = 1 + (diff(qh[-1] + q[i-1], ph[-1] + p[i-1]) - B - 1) // abs(diff(q[i], p[i])) + dp = p[i-1] + t*p[i] + dq = q[i-1] + t*q[i] + k = (N - qh[-1]) // dq + if k == 0: + return qh[-1], ph[-1] + if diff(dq, dp) != 0: + k = min(k, (B - diff(qh[-1], ph[-1])) // diff(dq, dp)) + qh.append(qh[-1] + k*dq) + ph.append(ph[-1] + k*dp) + return qh[-1], ph[-1] + def solve(A, B, N): - x, y = max_rem(A, N % A, B, N // A) + x, y = max_floor(A, N % A, B, N // A) return N // A - x, y ``` -!!! example "[CodeChef - Euler Sum](https://www.codechef.com/problems/ES)" +!!! example "[June Challenge 2017 - Euler Sum](https://www.codechef.com/problems/ES)" Compute $\sum\limits_{x=1}^N \lfloor ex \rfloor$, where $e = [2; 1, 2, 1, 1, 4, 1, 1, 6, 1, \dots, 1, 2n, 1, \dots]$ is the Euler's number and $N \leq 10^{4000}$. +??? hint "Solution" + This sum is equal to the number of lattice point $(x;y)$ such that $1 \leq x \leq N$ and $1 \leq y \leq ex$. + + After constructing the convex hull of the points below $y=ex$, this number can be computed using [Pick's theorem](../geometry/picks-theorem.md): -!!! example "[Kattis - It's a Mod, Mod, Mod, Mod World](https://open.kattis.com/problems/itsamodmodmodmodworld)" + === "C++" + ```cpp + // sum floor(k * x) for k in [1, N] and x = [a0; a1, a2, ...] + int sum_floor(auto a, int N) { + N++; + auto [ah, ph, qh] = hull(a, N); + + // The number of lattice points within a vertical right trapezoid + // on points (0; 0) - (0; y1) - (dx; y2) - (dx; 0) that has + // a+1 integer points on the segment (0; y1) - (dx; y2). + auto picks = [](int y1, int y2, int dx, int a) { + int b = y1 + y2 + a + dx; + int A = (y1 + y2) * dx; + return (A - b + 2) / 2 + b - (y2 + 1); + }; + + int ans = 0; + for(size_t i = 1; i < qh.size(); i++) { + ans += picks(ph[i - 1], ph[i], qh[i] - qh[i - 1], ah[i - 1]); + } + return ans - N; + } + ``` + === "Python" + ```py + # sum floor(k * x) for k in [1, N] and x = [a0; a1, a2, ...] + def sum_floor(a, N): + N += 1 + ah, ph, qh = hull(a, N) + + # The number of lattice points within a vertical right trapezoid + # on points (0; 0) - (0; y1) - (dx; y2) - (dx; 0) that has + # a+1 integer points on the segment (0; y1) - (dx; y2). + def picks(y1, y2, dx, a): + b = y1 + y2 + a + dx + A = (y1 + y2) * dx + return (A - b + 2) // 2 + b - (y2 + 1) + + ans = 0 + for i in range(1, len(qh)): + ans += picks(ph[i-1], ph[i], qh[i]-qh[i-1], ah[i-1]) + return ans - N + ``` + +!!! example "[NAIPC 2019 - It's a Mod, Mod, Mod, Mod World](https://open.kattis.com/problems/itsamodmodmodmodworld)" Given $p$, $q$ and $n$, compute $\sum\limits_{i=1}^n [p \cdot i \bmod q]$. -The connection between $\bmod$ and $\lfloor \cdot \rfloor$ is given as $a \bmod b = a - \lfloor \frac{a}{b} \rfloor b$. +??? hint "Solution" + This problem reduces to the previous one if you note that $a \bmod b = a - \lfloor \frac{a}{b} \rfloor b$. With this fact, the sum reduces to + + $$\sum\limits_{i=1}^n \left(p \cdot i - \left\lfloor \frac{p \cdot i}{q} \right\rfloor q\right) = \frac{pn(n+1)}{2}-q\sum\limits_{i=1}^n \left\lfloor \frac{p \cdot i}{q}\right\rfloor.$$ + + However, summing up $\lfloor rx \rfloor$ for $x$ from $1$ to $N$ is something that we're capable of from the previous problem. + + === "C++" + ```cpp + void solve(int p, int q, int N) { + cout << p * N * (N + 1) / 2 - q * sum_floor(fraction(p, q), N) << "\n"; + } + ``` + === "Python" + ```py + def solve(p, q, N): + return p * N * (N + 1) // 2 - q * sum_floor(fraction(p, q), N) + ``` !!! example "[Library Checker - Sum of Floor of Linear](https://judge.yosupo.jp/problem/sum_of_floor_of_linear)" Given $N$, $M$, $A$ and $B$, compute $\sum\limits_{i=0}^{N-1} \lfloor \frac{A \cdot i + B}{M} \rfloor$. -This one is a bit more tricky. We'll discuss possible approaches to tackle it further below. +??? hint "Solution" + This is the most technically troublesome problem so far. + + It is possible to use the same approach and construct the full convex hull of points below the line $y = \frac{Ax+B}{M}$. + + We already know how to solve it for $B = 0$. Moreover, we already know how to construct this convex hull up to the closest lattice point to this line on $[0, N-1]$ segment (this is done in the "Crime and Punishment" problem above. + + Now we should note that once we reached the closest point to the line, we can just assume that the line in fact passes through the closest point, as there are no other lattice points on $[0, N-1]$ in between the actual line and the line moved slightly below to pass through the closest point. + + That being said, to construct the full convex hull below the line $y=\frac{Ax+B}{M}$ on $[0, N-1]$, we can construct it up to the closest point to the line on $[0, N-1]$ and then continue as if the line passes through this point, reusing algorithm for constructing convex hull with $B=0$: + + === "Python" + ```py + # hull of lattice (x, y) such that C*y <= A*x+B + def hull(A, B, C, N): + def diff(x, y): + return C*y-A*x + a = fraction(A, C) + p, q = convergents(a) + ah = [] + ph = [B // C] + qh = [0] + + def insert(dq, dp): + k = (N - qh[-1]) // dq + if diff(dq, dp) > 0: + k = min(k, (B - diff(qh[-1], ph[-1])) // diff(dq, dp)) + ah.append(k) + qh.append(qh[-1] + k*dq) + ph.append(ph[-1] + k*dp) + + for i in range(1, len(q) - 1): + if i % 2 == 0: + while diff(qh[-1] + q[i+1], ph[-1] + p[i+1]) <= B: + t = (B - diff(qh[-1] + q[i+1], ph[-1] + p[i+1])) // abs(diff(q[i], p[i])) + dp = p[i+1] - t*p[i] + dq = q[i+1] - t*q[i] + if dq < 0 or qh[-1] + dq > N: + break + insert(dq, dp) + + insert(q[-1], p[-1]) + + for i in reversed(range(len(q))): + if i % 2 == 1: + while qh[-1] + q[i-1] <= N: + t = (N - qh[-1] - q[i-1]) // q[i] + dp = p[i-1] + t*p[i] + dq = q[i-1] + t*q[i] + insert(dq, dp) + return ah, ph, qh + ``` + +!!! example "[OKC 2 - From Modular to Rational](https://codeforces.com/gym/102354/problem/I)" + There is a rational number $\frac{p}{q}$ such that $1 \leq p, q \leq 10^9$. You may ask the value of $p q^{-1}$ modulo $m \sim 10^9$ for several prime numbers $m$. Recover $\frac{p}{q}$. + + _Equivalent formulation:_ Find $x$ that delivers the minimum of $Ax \;\bmod\; M$ for $1 \leq x \leq N$. + +??? hint "Solution" + Due to Chinese remainder theorem, asking the result modulo several prime numbers is the same as asking it modulo their product. Due to this, without loss of generality we'll assume that we know the remainder modulo sufficiently large number $m$. + + There could be several possible solutions $(p, q)$ to $p \equiv qr \pmod m$ for a given remainder $r$. However, if $(p_1, q_1)$ and $(p_2, q_2)$ are both the solutions then it also holds that $p_1 q_2 \equiv p_2 q_1 \pmod m$. Assuming that $\frac{p_1}{q_1} \neq \frac{p_2}{q_2}$ it means that $|p_1 q_2 - p_2 q_1|$ is at least $m$. + + In the statement we were told that $1 \leq p, q \leq 10^9$, so if both $p_1, q_1$ and $p_2, q_2$ are at most $10^9$, then the difference is at most $10^{18}$. For $m > 10^{18}$ it means that the solution $\frac{p}{q}$ with $1 \leq p, q \leq 10^9$ is unique, as a rational number. + + So, the problem boils down, given $r$ modulo $m$, to finding any $q$ such that $1 \leq q \leq 10^9$ and $qr \;\bmod\; m \leq 10^9$. + + This is effectively the same as finding $q$ that delivers the minimum possible $qr \bmod m$ for $1 \leq q \leq 10^9$. + + For $qr = km + b$ it means that we need to find a pair $(q, m)$ such that $1 \leq q \leq 10^9$ and $qr - km \geq 0$ is the minimum possible. + + Since $m$ is constant, we can divide by it and further restate it as find $q$ such that $1 \leq q \leq 10^9$ and $\frac{r}{m} q - k \geq 0$ is the minimum possible. + + In terms of continued fractions it means that $\frac{k}{q}$ is the best diophantine approximation to $\frac{r}{m}$ and it is sufficient to only check lower semiconvergents of $\frac{r}{m}$. + + === "Python" + ```py + # find Q that minimizes Q*r mod m for 1 <= k <= n < m + def mod_min(r, n, m): + a = fraction(r, m) + p, q = convergents(a) + for i in range(2, len(q)): + if i % 2 == 1 and (i + 1 == len(q) or q[i+1] > n): + t = (n - q[i-1]) // q[i] + return q[i-1] + t*q[i] + ``` + +!!! example "[SnackDown 2019 - Election Bait](https://www.codechef.com/SNCKEL19/problems/EBAIT)" + abc + +!!! example "[GCJ 2019, Round 2 - New Elements: Part 2](https://codingcompetitions.withgoogle.com/codejam/round/0000000000051679/0000000000146184)" + You're given $N$ positive integer pairs $(C_i, J_i)$. You need to find a positive integer pair $(x, y)$ such that $C_i x + J_i y$ is a strictly increasing sequence. + + Among such numbers, find the lexicographically minimum one. + + _Equivalent formulation_: $C_i x + J_i y$ must be positive for all $i$ ($C_i$ and $J_i$ not necessarily positive). +??? hint "Solution" + Rephrasing the statement, $A_i x + B_i y$ must be positive for all $i$, where $A_i = C_i - C_{i-1}$ and $B_i = J_i - J_{i-1}$. + + Among such equations we have three significant groups: + + 1. $A_i, B_i > 0$ can be ignored since we're looking for $x, y > 0$. + 2. $A_i, B_i \leq 0$ would provide "IMPOSSIBLE" as an answer. + 3. $A_i > 0$, $B_i \leq 0$ and $A_i \leq 0, B_i > 0$ bound possible values of $x$ and $y$ from two sides. + + Among two groups in the third point we should only leave one pair $(A_i, B_i)$ corresponding to the smallest (largest) slope. From 77733117ab3be72b9bfbce9f9b8dddee6e76b550 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Thu, 31 Mar 2022 13:19:05 +0200 Subject: [PATCH 43/45] + continued fractions article --- src/index.md | 1 + 1 file changed, 1 insertion(+) diff --git a/src/index.md b/src/index.md index 357b5ed99..cb757c537 100644 --- a/src/index.md +++ b/src/index.md @@ -50,6 +50,7 @@ Full list of updates: [Commit History](https://github.com/e-maxx-eng/e-maxx-eng/ - [Arbitrary-Precision Arithmetic](algebra/big-integer.md) - [Fast Fourier transform](algebra/fft.md) - [Operations on polynomials and series](algebra/polynomial.md) + - [Continued fractions](algebra/continued-fractions.md) ### Data Structures From b594051be666c0f73e5338211c4bed027115f6fa Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Thu, 31 Mar 2022 17:20:36 +0200 Subject: [PATCH 44/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 81 ++++++++++++++++++++++++++++-- 1 file changed, 76 insertions(+), 5 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index e2a2e2ace..e047c2ae2 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -797,15 +797,12 @@ Now that the most important facts and concepts were introduced, it is time to de return q[i-1] + t*q[i] ``` -!!! example "[SnackDown 2019 - Election Bait](https://www.codechef.com/SNCKEL19/problems/EBAIT)" - abc - !!! example "[GCJ 2019, Round 2 - New Elements: Part 2](https://codingcompetitions.withgoogle.com/codejam/round/0000000000051679/0000000000146184)" You're given $N$ positive integer pairs $(C_i, J_i)$. You need to find a positive integer pair $(x, y)$ such that $C_i x + J_i y$ is a strictly increasing sequence. - Among such numbers, find the lexicographically minimum one. + Among such pairs, find the lexicographically minimum one. - _Equivalent formulation_: $C_i x + J_i y$ must be positive for all $i$ ($C_i$ and $J_i$ not necessarily positive). + _Equivalent formulation:_ You're given $\frac{0}{1} \leq \frac{p_0}{q_0} < \frac{p_1}{q_1} \leq \frac{1}{0}$. Find the rational number $\frac{p}{q}$ such that $(q; p)$ is lexicographically smallest and $\frac{p_0}{q_0} < \frac{p}{q} < \frac{p_1}{q_1}$. ??? hint "Solution" Rephrasing the statement, $A_i x + B_i y$ must be positive for all $i$, where $A_i = C_i - C_{i-1}$ and $B_i = J_i - J_{i-1}$. @@ -816,3 +813,77 @@ Now that the most important facts and concepts were introduced, it is time to de 3. $A_i > 0$, $B_i \leq 0$ and $A_i \leq 0, B_i > 0$ bound possible values of $x$ and $y$ from two sides. Among two groups in the third point we should only leave one pair $(A_i, B_i)$ corresponding to the smallest (largest) slope. + + Now the problem is as follows: given $\frac{p_0}{q_0} < \frac{p_1}{q_1}$, find a fraction $\frac{p}{q}$ such that $(q;p)$ is lexicographically smallest and $\frac{p_0}{q_0} < \frac{p}{q} < \frac{p_1}{q_1}$. + + In terms of the Stern-Brocot tree it means that we need to find the LCA of $\frac{p_0}{q_0}$ and $\frac{p_1}{q_1}$. Due to the connection between Stern-Brocot tree and continued fraction, this LCA would roughly correspond to the largest common prefix of continued fraction representations for $\frac{p_0}{q_0}$ and $\frac{p_1}{q_1}$. + + So, if $\frac{p_0}{q_0} = [a_0; a_1, \dots, a_{k-1}, a_k, \dots]$ and $\frac{p_1}{q_1} = [a_0; a_1, \dots, a_{k-1}, b_k, \dots]$, the LCA in most cases is $[a_0; a_1, \dots, \min(a_k, b_k)+1]$. + + The solution above is true for $r_0$ and $r_1$ being irrational numbers. However, for rational $r_0$ and $r_1$, one of them could be the LCA itself which would require us to casework it. To simplify the solution for rational $r_0$ and $r_1$, however, it is possible to use continued fraction representation of $r_0 + \varepsilon$ and $r_1 - \varepsilon$ for $\varepsilon \sim 0$. + + === "Python" + ```py + # [a0; a1, ..., ak] -> [a0, a1, ..., ak-1, 1] + def expand(a): + a[-1] -= 1 + a.append(1) + + def add_eps(a): + # make sure that adding new item to a would increase p/q + if len(a) % 2 == 0: + expand(a) + a.append(float('inf')) # p0/q0 + eps + return a + + def sub_eps(a): + # make sure that adding new item to a would decrease p/q + if len(a) % 2 == 1: + expand(a) + a.append(float('inf')) # p1/q1 - eps + return a + + # finds lexicographically smallest (q, p) + # such that p0/q0 < p/q < p1/q1 + def middle(p0, q0, p1, q1): + a0 = add_eps(fraction(p0, q0)) + a1 = sub_eps(fraction(p1, q1)) + a = [] + for i in range(min(len(a0), len(a1))): + a.append(min(a0[i], a1[i])) + if a0[i] != a1[i]: + break + a[-1] += 1 + p, q = convergents(a) + return p[-1], q[-1] + + def solve(): + n = int(input()) + C = [0] * n + J = [0] * n + # p0/q0 < y/x < p1/q1 + p0, q0 = 0, 1 + p1, q1 = 1, 0 + fail = False + for i in range(n): + C[i], J[i] = map(int, input().split()) + if i > 0: + A = C[i] - C[i-1] + B = J[i] - J[i-1] + if A <= 0 and B <= 0: + fail = True + elif B > 0 and A < 0: # y/x > (-A)/B if B > 0 + if (-A)*q0 > p0*B: + p0, q0 = -A, B + elif B < 0 and A > 0: # y/x < A/(-B) if B < 0 + if A*q1 < p1*(-B): + p1, q1 = A, -B + if p0*q1 >= p1*q0 or fail: + return 'IMPOSSIBLE' + + p, q = middle(p0, q0, p1, q1) + return str(q) + ' ' + str(p) + ``` + +!!! example "[SnackDown 2019 - Election Bait](https://www.codechef.com/SNCKEL19/problems/EBAIT)" + abc From 8abb10666e1b6059408a9d378ac27bc4a1940a8b Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Thu, 31 Mar 2022 18:17:31 +0200 Subject: [PATCH 45/45] Update continued-fractions.md --- src/algebra/continued-fractions.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/algebra/continued-fractions.md b/src/algebra/continued-fractions.md index e047c2ae2..d3dd62dcb 100644 --- a/src/algebra/continued-fractions.md +++ b/src/algebra/continued-fractions.md @@ -885,5 +885,6 @@ Now that the most important facts and concepts were introduced, it is time to de return str(q) + ' ' + str(p) ``` -!!! example "[SnackDown 2019 - Election Bait](https://www.codechef.com/SNCKEL19/problems/EBAIT)" - abc +## Practise problems + +* [SnackDown 2019 - Election Bait](https://www.codechef.com/SNCKEL19/problems/EBAIT)