Post · 45 min read· pp. 140–168

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).

Besides that, continued fractions are closely related to Euclidean algorithm which makes them useful in a bunch of number-theoretical problems.

Continued fraction representation

Definition

Let a0,a1,…,ak∈Za_0, a_1, \dots, a_k \in \mathbb Z and a1,a2,…,ak≥1a_1, a_2, \dots, a_k \geq 1. Then the expression

r=a0+1a1+1⋯+1ak,r=a_0 + \frac{1}{a_1 + \frac{1}{\dots + \frac{1}{a_k}}},

is called the continued fraction representation of the rational number rr and is denoted shortly as r=[a0;a1,a2,…,ak]r=[a_0;a_1,a_2,\dots,a_k].

Example

Let r=53r = \frac{5}{3}. There are two ways to represent it as a continued fraction:

r=[1;1,1,1]=1+11+11+11,r=[1;1,2]=1+11+12.\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 22 ways:

r=[a0;a1,…,ak,1]=[a0;a1,…,ak+1].r = [a_0;a_1,\dots,a_k,1] = [a_0;a_1,\dots,a_k+1].

Moreover, the length kk of such continued fraction is estimated as k=O(log⁡min⁡(p,q))k = O(\log \min(p, q)) for r=pqr=\frac{p}{q}.

The reasoning behind this will be clear once we delve into the details of the continued fraction construction.

Definition

Let a0,a1,a2,…a_0,a_1,a_2, \dots be an integer sequence such that a1,a2,⋯≥1a_1, a_2, \dots \geq 1. Let rk=[a0;a1,…,ak]r_k = [a_0; a_1, \dots, a_k]. Then the expression

r=a0+1a1+1a2+…=lim⁡k→∞rk.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 rr and is denoted shortly as r=[a0;a1,a2,… ]r = [a_0;a_1,a_2,\dots].

Note that for r=[a0;a1,… ]r=[a_0;a_1,\dots] and integer kk, it holds that r+k=[a0+k;a1,… ]r+k = [a_0+k; a_1, \dots].

Another important observation is that 1r=[0;a0,a1,… ]\frac{1}{r}=[0;a_0, a_1, \dots] when a0>0a_0 > 0 and 1r=[a1;a2,… ]\frac{1}{r} = [a_1; a_2, \dots] when a0=0a_0 = 0.

Definition

In the definition above, rational numbers r0,r1,r2,…r_0, r_1, r_2, \dots are called the convergents of rr.

Correspondingly, individual rk=[a0;a1,…,ak]=pkqkr_k = [a_0; a_1, \dots, a_k] = \frac{p_k}{q_k} is called the kk-th convergent of rr.

Example

Consider r=[1;1,1,1,… ]r = [1; 1, 1, 1, \dots]. It can be proven by induction that rk=Fk+2Fk+1r_k = \frac{F_{k+2}}{F_{k+1}}, where FkF_k is the Fibonacci sequence defined as F0=0F_0 = 0, F1=1F_1 = 1 and Fk=Fk−1+Fk−2F_{k} = F_{k-1} + F_{k-2}. From the Binet's formula, it is known that

rk=ϕk+2−ψk+2ϕk+1−ψk+1,r_k = \frac{\phi^{k+2} - \psi^{k+2}}{\phi^{k+1} - \psi^{k+1}},

where ϕ=1+52≈1.618\phi = \frac{1+\sqrt{5}}{2} \approx 1.618 is the golden ratio and ψ=1−52=−1ϕ≈−0.618\psi = \frac{1-\sqrt{5}}{2} = -\frac{1}{\phi} \approx -0.618. Thus,

r=1+11+11+…=lim⁡k→∞rk=ϕ=1+52.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 rr would be to solve the equation

r=1+1r  ⟹  r2=r+1.r = 1+\frac{1}{r} \implies r^2 = r + 1.

Definition

Let rk=[a0;a1,…,ak−1,ak]r_k = [a_0; a_1, \dots, a_{k-1}, a_k]. The numbers [a0;a1,…,ak−1,t][a_0; a_1, \dots, a_{k-1}, t] for 1≤t≤ak1 \leq t \leq a_k are called semiconvergents.

We will typically refer to (semi)convergents that are greater than rr as upper (semi)convergents and to those that are less than rr as lower (semi)convergents.

Definition

Complementary to convergents, we define the complete quotients as sk=[ak;ak+1,ak+2,… ]s_k = [a_k; a_{k+1}, a_{k+2}, \dots].

Correspondingly, we will call an individual sks_k the kk-th complete quotient of rr.

From the definitions above, one can conclude that sk≥1s_k \geq 1 for k≥1k \geq 1.

Treating [a0;a1,…,ak][a_0; a_1, \dots, a_k] as a formal algebraic expression and allowing arbitrary real numbers instead of aia_i, we obtain

r=[a0;a1,…,ak−1,sk].r = [a_0; a_1, \dots, a_{k-1}, s_k].

In particular, r=[s0]=s0r = [s_0] = s_0. On the other hand, we can express sks_k as

sk=[ak;sk+1]=ak+1sk+1,s_k = [a_k; s_{k+1}] = a_k + \frac{1}{s_{k+1}},

meaning that we can compute ak=⌊sk⌋a_k = \lfloor s_k \rfloor and sk+1=(sk−ak)−1s_{k+1} = (s_k - a_k)^{-1} from sks_k.

The sequence a0,a1,…a_0, a_1, \dots is well-defined unless sk=aks_k=a_k which only happens when rr is a rational number.

Thus the continued fraction representation is uniquely defined for any irrational number rr.

Implementation

In the code snippets we will mostly assume finite continued fractions.

From sks_k, the transition to sk+1s_{k+1} looks like

sk=⌊sk⌋+1sk+1.s_k =\left\lfloor s_k \right\rfloor + \frac{1}{s_{k+1}}.

From this expression, the next complete quotient sk+1s_{k+1} is obtained as

sk+1=(sk−⌊sk⌋)−1.s_{k+1} = \left(s_k-\left\lfloor s_k\right\rfloor\right)^{-1}.

For sk=pqs_k=\frac{p}{q} it means that

sk+1=(pq−⌊pq⌋)−1=qp−q⋅⌊pq⌋=qp mod 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, the computation of a continued fraction representation for r=pqr=\frac{p}{q} follows the steps of the Euclidean algorithm for pp and qq.

From this also follows that gcd⁡(pk,qk)=1\gcd(p_k, q_k) = 1 for pkqk=[a0;a1,…,ak]\frac{p_k}{q_k} = [a_0; a_1, \dots, a_k]. Hence, convergents are always irreducible.

C++Python

text
auto fraction(int p, int q) {
    vector<int> a;
    while(q) {
        a.push_back(p / q);
        tie(p, q) = make_pair(q, p % q);
    }
    return a;
}
text
def fraction(p, q):
    a = []
    while q:
        a.append(p // q)
        p, q = q, p % q
    return a

Key results

To provide some motivation for further study of continued fraction, we give some key facts now.

Recurrence

For the convergents rk=pkqkr_k = \frac{p_k}{q_k}, the following recurrence stands, allowing their fast computation:

pkqk=akpk−1+pk−2akqk−1+qk−2,\frac{p_k}{q_k}=\frac{a_k p_{k-1} + p_{k-2}}{a_k q_{k-1} + q_{k-2}},

where p−1q−1=10\frac{p_{-1}}{q_{-1}}=\frac{1}{0} and p−2q−2=01\frac{p_{-2}}{q_{-2}}=\frac{0}{1}.

Deviations

The deviation of rk=pkqkr_k = \frac{p_k}{q_k} from rr can be generally estimated as

∣pkqk−r∣≤1qkqk+1≤1qk2.\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 qkq_k, we obtain alternate estimation:

∣pk−qkr∣≤1qk+1.|p_k - q_k r| \leq \frac{1}{q_{k+1}}.

From the recurrence above it follows that qkq_k grows at least as fast as Fibonacci numbers.

On the picture below you may see the visualization of how convergents rkr_k approach r=1+52r=\frac{1+\sqrt 5}{2}:

r=1+52r=\frac{1+\sqrt 5}{2} is depicted by blue dotted line. Odd convergents approach it from above and even convergents approach it from below.

Lattice hulls

Consider convex hulls of points above and below the line y=rxy=rx.

Odd convergents (qk;pk)(q_k;p_k) are the vertices of the upper hull, while the even convergents (qk;pk)(q_k;p_k) are the vertices of the bottom hull.

All integers vertices on the hulls are obtained as (q;p)(q;p) such that

pq=tpk−1+pk−2tqk−1+qk−2\frac{p}{q} = \frac{tp_{k-1} + p_{k-2}}{tq_{k-1} + q_{k-2}}

for integer 0≤t≤ak0 \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 semiconvergents (intermediate gray points) of r=97r=\frac{9}{7}.

Best approximations

Let pq\frac{p}{q} be the fraction to minimize ∣r−pq∣\left|r-\frac{p}{q}\right| subject to q≤xq \leq x for some xx.

Then pq\frac{p}{q} is a semiconvergent of rr.

The last fact allows to find the best rational approximations of rr by checking its semiconvergents.

Below you will find the further explanation and a bit of intuition and interpretation for these facts.

Convergents

Let's take a closer look at the convergents that were defined earlier. For r=[a0,a1,a2,… ]r=[a_0, a_1, a_2, \dots], its convergents are

r0=[a0],r1=[a0,a1],…,rk=[a0,a1,…,ak].\begin{gather} r_0=[a_0],\\r_1=[a_0, a_1],\\ \dots,\\ r_k=[a_0, a_1, \dots, a_k]. \end{gather}

Convergents are the core concept of continued fractions, so it is important to study their properties.

For the number rr, its kk-th convergent rk=pkqkr_k = \frac{p_k}{q_k} can be computed as

rk=Pk(a0,a1,…,ak)Pk−1(a1,…,ak)=akpk−1+pk−2akqk−1+qk−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 Pk(a0,…,ak)P_k(a_0,\dots,a_k) is the continuant, a multivariate polynomial defined as

Pk(x0,x1,…,xk)=det⁡[xk10…0−1xk−11…00−1x2.⋮⋮⋮.⋱100…−1x0].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, rkr_k is a weighted mediant of rk−1r_{k-1} and rk−2r_{k-2}.

For consistency, two additional convergents r−1=10r_{-1} = \frac{1}{0} and r−2=01r_{-2} = \frac{0}{1} are defined.

Detailed explanation

The numerator and the denominator of rkr_k can be seen as multivariate polynomials of a0,a1,…,aka_0, a_1, \dots, a_k:

rk=Pk(a0,a1,…,ak)Qk(a0,a1,…,ak).r_k = \frac{P_k(a_0, a_1, \dots, a_k)}{Q_k(a_0,a_1, \dots, a_k)}.

From the definition of convergents,

rk=a0+1[a1;a2,…,ak]=a0+Qk−1(a1,…,ak)Pk−1(a1,…,ak)=a0Pk−1(a1,…,ak)+Qk−1(a1,…,ak)Pk−1(a1,…,ak).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)}.

From this follows Qk(a0,…,ak)=Pk−1(a1,…,ak)Q_k(a_0, \dots, a_k) = P_{k-1}(a_1, \dots, a_k). This yields the relation

Pk(a0,…,ak)=a0Pk−1(a1,…,ak)+Pk−2(a2,…,ak).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).

Initially, r0=a01r_0 = \frac{a_0}{1} and r1=a0a1+1a1r_1 = \frac{a_0 a_1 + 1}{a_1}, thus

P0(a0)=a0,P1(a0,a1)=a0a1+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 convenient to define P−1=1P_{-1} = 1 and P−2=0P_{-2}=0 and formally say that r−1=10r_{-1} = \frac{1}{0} and r−2=01r_{-2}=\frac{0}{1}.

From numerical analysis, it is known that the determinant of an arbitrary tridiagonal matrix

Tk=det⁡[a0b00…0c0a1b1…00c1a2.⋮⋮⋮.⋱ck−100…bk−1ak]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 Tk=akTk−1−bk−1ck−1Tk−2T_k = a_k T_{k-1} - b_{k-1} c_{k-1} T_{k-2}. Comparing it to PkP_k, we get a direct expression

Pk=det⁡[xk10…0−1xk−11…00−1x2.⋮⋮⋮.⋱100…−1x0].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 .}

This polynomial is also known as the continuant 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:

Pk(a0,…,ak)=akPk−1(a0,…,ak−1)+Pk−2(a0,…,ak−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

We will compute the convergents as a pair of sequences p−2,p−1,p0,p1,…,pkp_{-2}, p_{-1}, p_0, p_1, \dots, p_k and q−2,q−1,q0,q1,…,qkq_{-2}, q_{-1}, q_0, q_1, \dots, q_k:

C++Python

text
auto convergents(vector<int> a) {
    vector<int> p = {0, 1};
    vector<int> 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);
}
text
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

Trees of continued fractions

There are two major ways to unite all possible continued fractions into useful tree structures.

Stern-Brocot tree

The Stern-Brocot tree is a binary search tree that contains all distinct positive rational numbers.

The tree generally looks as follows:

The image by Aaron Rotenberg is licensed under CC BY-SA 3.0

Fractions 01\frac{0}{1} and 10\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 a+cb+d\frac{a+c}{b+d} of two fractions ab\frac{a}{b} and cd\frac{c}{d} above it.

The recurrence pkqk=akpk−1+pk−2akqk−1+qk−2\frac{p_k}{q_k}=\frac{a_k p_{k-1} + p_{k-2}}{a_k q_{k-1} + q_{k-2}} means that the continued fraction representation encodes the path to pkqk\frac{p_k}{q_k} in the tree. To find [a0;a1,…,ak,1][a_0; a_1, \dots, a_{k}, 1], one has to make a0a_0 moves to the right, a1a_1 moves to the left, a2a_2 moves to the right and so on up to aka_k.

The parent of [a0;a1,…,ak,1][a_0; a_1, \dots, a_k,1] then is the fraction obtained by taking one step back in the last used direction.

In other words, it is [a0;a1,…,ak−1,1][a_0; a_1, \dots, a_k-1,1] when ak>1a_k > 1 and [a0;a1,…,ak−1,1][a_0; a_1, \dots, a_{k-1}, 1] when ak=1a_k = 1.

Thus the children of [a0;a1,…,ak,1][a_0; a_1, \dots, a_k, 1] are [a0;a1,…,ak+1,1][a_0; a_1, \dots, a_k+1, 1] and [a0;a1,…,ak,1,1][a_0; a_1, \dots, a_k, 1, 1].

Let's index the Stern-Brocot tree. The root vertex is assigned an index 11. Then for a vertex vv, the index of its left child is assigned by changing the leading bit of vv from 11 to 1010 and for the right child, it's assigned by changing the leading bit from 11 to 1111:

In this indexing, the continued fraction representation of a rational number specifies the run-length encoding of its binary index.

For 52=[2;2]=[2;1,1]\frac{5}{2} = [2;2] = [2;1,1], its index is 101121011_2 and its run-length encoding, considering bits in the ascending order, is [2;1,1][2;1,1].

Another example is 25=[0;2,2]=[0;2,1,1]\frac{2}{5} = [0;2,2]=[0;2,1,1], which has index 110021100_2 and its run-length encoding is, indeed, [0;2,2][0;2,2].

It is worth noting that the Stern-Brocot tree is, in fact, a treap. That is, it is a binary search tree by pq\frac{p}{q}, but it is a heap by both pp and qq.

Comparing continued fractions

You're given A=[a0;a1,…,an]A=[a_0; a_1, \dots, a_n] and B=[b0;b1,…,bm]B=[b_0; b_1, \dots, b_m]. Which fraction is smaller?

Solution

Assume for now that AA and BB are irrational and their continued fraction representations denote an infinite descent in the Stern-Brocot tree.

As we already mentioned, in this representation a0a_0 denotes the number of right turns in the descent, a1a_1 denotes the number of consequent left turns and so on. Therefore, when we compare aka_k and bkb_k, if ak=bka_k = b_k we should just move on to comparing ak+1a_{k+1} and bk+1b_{k+1}. Otherwise, if we're at right descents, we should check if ak<bka_k < b_k and if we're at left descents, we should check if ak>bka_k > b_k to tell whether A<BA < B.

In other words, for irrational AA and BB it would be A<BA < B if and only if (a0,−a1,a2,−a3,… )<(b0,−b1,b2,−b3,… )(a_0, -a_1, a_2, -a_3, \dots) < (b_0, -b_1, b_2, -b_3, \dots) with lexicographical comparison.

Now, formally using ∞\infty as an element of continued fraction representation it is possible to emulate irrational numbers A−εA-\varepsilon and A+εA+\varepsilon, that is, elements that are smaller (greater) than AA, but greater (smaller) than any other real number. Specifically, for A=[a0;a1,…,an]A=[a_0; a_1, \dots, a_n], one of these two elements can be emulated as [a0;a1,…,an,∞][a_0; a_1, \dots, a_n, \infty] and the other can be emulated as [a0;a1,…,an−1,1,∞][a_0; a_1, \dots, a_n - 1, 1, \infty].

Which one corresponds to A−εA-\varepsilon and which one to A+εA+\varepsilon can be determined by the parity of nn or by comparing them as irrational numbers.

Python

text
# check if a < b assuming that a[-1] = b[-1] = infty and a != b
def less(a, b):
    a = [(-1)**i*a[i] for i in range(len(a))]
    b = [(-1)**i*b[i] for i in range(len(b))]
    return a < b

# [a0; a1, ..., ak] -> [a0, a1, ..., ak-1, 1]
def expand(a):
    if a: # empty a = inf
        a[-1] -= 1
        a.append(1)
    return a

# return a-eps, a+eps
def pm_eps(a):
    b = expand(a.copy())
    a.append(float('inf'))
    b.append(float('inf'))
    return (a, b) if less(a, b) else (b, a)

Best inner point

You're given 01≤p0q0<p1q1≤10\frac{0}{1} \leq \frac{p_0}{q_0} < \frac{p_1}{q_1} \leq \frac{1}{0}. Find the rational number pq\frac{p}{q} such that (q;p)(q; p) is lexicographically smallest and p0q0<pq<p1q1\frac{p_0}{q_0} < \frac{p}{q} < \frac{p_1}{q_1}.

Solution

In terms of the Stern-Brocot tree it means that we need to find the LCA of p0q0\frac{p_0}{q_0} and p1q1\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 p0q0\frac{p_0}{q_0} and p1q1\frac{p_1}{q_1}.

So, if p0q0=[a0;a1,…,ak−1,ak,… ]\frac{p_0}{q_0} = [a_0; a_1, \dots, a_{k-1}, a_k, \dots] and p1q1=[a0;a1,…,ak−1,bk,… ]\frac{p_1}{q_1} = [a_0; a_1, \dots, a_{k-1}, b_k, \dots] are irrational numbers, the LCA is [a0;a1,…,min⁡(ak,bk)+1][a_0; a_1, \dots, \min(a_k, b_k)+1].

For rational r0r_0 and r1r_1, one of them could be the LCA itself which would require us to casework it. To simplify the solution for rational r0r_0 and r1r_1, it is possible to use continued fraction representation of r0+εr_0 + \varepsilon and r1−εr_1 - \varepsilon which was derived in the previous problem.

Python

text
# finds lexicographically smallest (q, p)
# such that p0/q0 < p/q < p1/q1
def middle(p0, q0, p1, q1):
    a0 = pm_eps(fraction(p0, q0))[1]
    a1 = pm_eps(fraction(p1, q1))[0]
    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]

GCJ 2019, Round 2 - New Elements: Part 2

You're given NN positive integer pairs (Ci,Ji)(C_i, J_i). You need to find a positive integer pair (x,y)(x, y) such that Cix+JiyC_i x + J_i y is a strictly increasing sequence.

Among such pairs, find the lexicographically minimum one.

Solution

Rephrasing the statement, Aix+BiyA_i x + B_i y must be positive for all ii, where Ai=Ci−Ci−1A_i = C_i - C_{i-1} and Bi=Ji−Ji−1B_i = J_i - J_{i-1}.

Among such equations we have four significant groups for Aix+Biy>0A_i x + B_i y > 0:

  1. Ai,Bi>0A_i, B_i > 0 can be ignored since we're looking for x,y>0x, y > 0.
  2. Ai,Bi≤0A_i, B_i \leq 0 would provide "IMPOSSIBLE" as an answer.
  3. Ai>0A_i > 0, Bi≤0B_i \leq 0. Such constraints are equivalent to yx<Ai−Bi\frac{y}{x} < \frac{A_i}{-B_i}.
  4. Ai≤0A_i \leq 0, Bi>0B_i > 0. Such constraints are equivalent to yx>−AiBi\frac{y}{x} > \frac{-A_i}{B_i}.

Let p0q0\frac{p_0}{q_0} be the largest −AiBi\frac{-A_i}{B_i} from the fourth group and p1q1\frac{p_1}{q_1} be the smallest Ai−Bi\frac{A_i}{-B_i} from the third group.

The problem is now, given p0q0<p1q1\frac{p_0}{q_0} < \frac{p_1}{q_1}, find a fraction pq\frac{p}{q} such that (q;p)(q;p) is lexicographically smallest and p0q0<pq<p1q1\frac{p_0}{q_0} < \frac{p}{q} < \frac{p_1}{q_1}.

Python

text
    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)

Calkin-Wilf tree

A somewhat simpler way to organize continued fractions in a binary tree is the Calkin-Wilf tree.

The tree generally looks like this:

The image by Olli Niemitalo, Proz is licensed under CC0 1.0

In the root of the tree, the number 11\frac{1}{1} is located. Then, for the vertex with a number pq\frac{p}{q}, its children are pp+q\frac{p}{p+q} and p+qq\frac{p+q}{q}.

Unlike the Stern-Brocot tree, the Calkin-Wilf tree is not a binary search tree, so it can't be used to perform rational binary search.

In the Calkin-Wilf tree, the direct parent of a fraction pq\frac{p}{q} is p−qq\frac{p-q}{q} when p>qp>q and pq−p\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 complete quotients. If sk=pqs_k = \frac{p}{q}, then sk+1=qpmod  q=qp−⌊p/q⌋⋅qs_{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 sk=pqs_k = \frac{p}{q} to its parent in the Calkin-Wilf tree when p>qp > q, we will end up in pmod  qq=1sk+1\frac{p \mod q}{q} = \frac{1}{s_{k+1}}. If we continue doing so, we will end up in sk+2s_{k+2}, then 1sk+3\frac{1}{s_{k+3}} and so on. From this we can deduce that:

  1. When a0>0a_0> 0, the direct parent of [a0;a1,…,ak][a_0; a_1, \dots, a_k] in the Calkin-Wilf tree is p−qq=[a0−1;a1,…,ak]\frac{p-q}{q}=[a_0 - 1; a_1, \dots, a_k].
  2. When a0=0a_0 = 0 and a1>1a_1 > 1, its direct parent is pq−p=[0;a1−1,a2,…,ak]\frac{p}{q-p} = [0; a_1 - 1, a_2, \dots, a_k].
  3. And when a0=0a_0 = 0 and a1=1a_1 = 1, its direct parent is pq−p=[a2;a3,…,ak]\frac{p}{q-p} = [a_2; a_3, \dots, a_k].

Correspondingly, children of pq=[a0;a1,…,ak]\frac{p}{q} = [a_0; a_1, \dots, a_k] are

  1. p+qq=1+pq\frac{p+q}{q}=1+\frac{p}{q}, which is [a0+1;a1,…,ak][a_0+1; a_1, \dots, a_k],
  2. pp+q=11+qp\frac{p}{p+q} = \frac{1}{1+\frac{q}{p}}, which is [0,1,a0,a1,…,ak][0, 1, a_0, a_1, \dots, a_k] for a0>0a_0 > 0 and [0,a1+1,a2,…,ak][0, a_1+1, a_2, \dots, a_k] for a0=0a_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 11, and the children of the vertex vv have indices 2v2v and 2v+12v+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.

Convergence

For the number rr and its kk-th convergent rk=pkqkr_k=\frac{p_k}{q_k} the following formula stands:

rk=a0+∑i=1k(−1)i−1qiqi−1.r_k = a_0 + \sum\limits_{i=1}^k \frac{(-1)^{i-1}}{q_i q_{i-1}}.

In particular, it means that

rk−rk−1=(−1)k−1qkqk−1r_k - r_{k-1} = \frac{(-1)^{k-1}}{q_k q_{k-1}}

and

pkqk−1−pk−1qk=(−1)k−1.p_k q_{k-1} - p_{k-1} q_k = (-1)^{k-1}.

From this we can conclude that

∣r−pkqk∣≤1qk+1qk≤1qk2.\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 rkr_k and rk+1r_{k+1} are generally located on different sides of rr, thus

∣r−rk∣=∣rk−rk+1∣−∣r−rk+1∣≤∣rk−rk+1∣.|r-r_k| = |r_k-r_{k+1}|-|r-r_{k+1}| \leq |r_k - r_{k+1}|.
Detailed explanation

To estimate ∣r−rk∣|r-r_k|, we start by estimating the difference between adjacent convergents. By definition,

pkqk−pk−1qk−1=pkqk−1−pk−1qkqkqk−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 pkp_k and qkq_k in the numerator with their recurrences, we get

pkqk−1−pk−1qk=(akpk−1+pk−2)qk−1−pk−1(akqk−1+qk−2)=pk−2qk−1−pk−1qk−2,\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 rk−rk−1r_k - r_{k-1} is always the negated numerator of rk−1−rk−2r_{k-1} - r_{k-2}. It, in turn, equals to 11 for

r1−r0=(a0+1a1)−a0=1a1,r_1 - r_0=\left(a_0+\frac{1}{a_1}\right)-a_0=\frac{1}{a_1},

thus

rk−rk−1=(−1)k−1qkqk−1.r_k - r_{k-1} = \frac{(-1)^{k-1}}{q_k q_{k-1}}.

This yields an alternative representation of rkr_k as a partial sum of infinite series:

rk=(rk−rk−1)+⋯+(r1−r0)+r0=a0+∑i=1k(−1)i−1qiqi−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 qkq_k monotonously increases at least as fast as Fibonacci numbers, thus

r=lim⁡k→∞rk=a0+∑i=1∞(−1)i−1qiqi−1r = \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

r−rk=∑i=k+1∞(−1)i−1qiqi−1r-r_k = \sum\limits_{i=k+1}^\infty \frac{(-1)^{i-1}}{q_i q_{i-1}}

has the same sign as (−1)k(-1)^k due to how fast qiqi−1q_i q_{i-1} decreases. Hence even-indexed rkr_k approach rr from below while odd-indexed rkr_k approach it from above:

Convergents of r=ϕ=1+52=[1;1,1,… ]r=\phi = \frac{1+\sqrt{5}}{2}=[1;1,1,\dots] and their distance from rr.

From this picture we can see that

∣r−rk∣=∣rk−rk+1∣−∣r−rk+1∣≤∣rk−rk+1∣,|r-r_k| = |r_k - r_{k+1}| - |r-r_{k+1}| \leq |r_k - r_{k+1}|,

thus the distance between rr and rkr_k is never larger than the distance between rkr_k and rk+1r_{k+1}:

∣r−pkqk∣≤1qkqk+1≤1qk2.\left|r-\frac{p_k}{q_k}\right| \leq \frac{1}{q_k q_{k+1}} \leq \frac{1}{q_k^2}.

Extended Euclidean?

You're given A,B,C∈ZA, B, C \in \mathbb Z. Find x,y∈Zx, y \in \mathbb Z such that Ax+By=CAx + By = C.

Solution

Although this problem is typically solved with the extended Euclidean algorithm, there is a simple and straightforward solution with continued fractions.

Let AB=[a0;a1,…,ak]\frac{A}{B}=[a_0; a_1, \dots, a_k]. It was proved above that pkqk−1−pk−1qk=(−1)k−1p_k q_{k-1} - p_{k-1} q_k = (-1)^{k-1}. Substituting pkp_k and qkq_k with AA and BB, we get

Aqk−1−Bpk−1=(−1)k−1g,Aq_{k-1} - Bp_{k-1} = (-1)^{k-1} g,

where g=gcd⁡(A,B)g = \gcd(A, B). If CC is divisible by gg, then the solution is x=(−1)k−1Cgqk−1x = (-1)^{k-1}\frac{C}{g} q_{k-1} and y=(−1)kCgpk−1y = (-1)^{k}\frac{C}{g} p_{k-1}.

Python

text
# return (x, y) such that Ax+By=C
# assumes that such (x, y) exists
def dio(A, B, C):
    p, q = convergents(fraction(A, B))
    C //= A // p[-1] # divide by gcd(A, B)
    t = (-1) if len(p) % 2 else 1
    return t*C*q[-2], -t*C*p[-2]

Linear fractional transformations

Another important concept for continued fractions are the so-called linear fractional transformations.

Definition

A linear fractional transformation is a function f:R→Rf : \mathbb R \to \mathbb R such that f(x)=ax+bcx+df(x) = \frac{ax+b}{cx+d} for some a,b,c,d∈Ra,b,c,d \in \mathbb R.

A composition (L0∘L1)(x)=L0(L1(x))(L_0 \circ L_1)(x) = L_0(L_1(x)) of linear fractional transforms L0(x)=a0x+b0c0x+d0L_0(x)=\frac{a_0 x + b_0}{c_0 x + d_0} and L1(x)=a1x+b1c1x+d1L_1(x)=\frac{a_1 x + b_1}{c_1 x + d_1} is itself a linear fractional transform:

a0a1x+b1c1x+d1+b0c0a1x+b1c1x+d1+d0=a0(a1x+b1)+b0(c1x+d1)c0(a1x+b1)+d0(c1x+d1)=(a0a1+b0c1)x+(a0b1+b0d1)(c0a1+d0c1)x+(c0b1+d0d1).\frac{a_0\frac{a_1 x + b_1}{c_1 x + d_1} + b_0}{c_0 \frac{a_1 x + b_1}{c_1 x + d_1} + d_0} = \frac{a_0(a_1 x + b_1) + b_0 (c_1 x + d_1)}{c_0 (a_1 x + b_1) + d_0 (c_1 x + d_1)} = \frac{(a_0 a_1 + b_0 c_1) x + (a_0 b_1 + b_0 d_1)}{(c_0 a_1 + d_0 c_1) x + (c_0 b_1 + d_0 d_1)}.

Inverse of a linear fractional transform, is also a linear fractional transform:

y=ax+bcx+d  ⟺  y(cx+d)=ax+b  ⟺  x=−dy−bcy−a.y = \frac{ax+b}{cx+d} \iff y(cx+d) = ax + b \iff x = -\frac{dy-b}{cy-a}.

DMOPC '19 Contest 7 P4 - Bob and Continued Fractions

You're given an array of positive integers a1,…,ana_1, \dots, a_n. You need to answer mm queries. Each query is to compute [al;al+1,…,ar][a_l; a_{l+1}, \dots, a_r].

Solution

We can solve this problem with the segment tree if we're able to concatenate continued fractions.

It's generally true that [a0;a1,…,ak,b0,b1,…,bk]=[a0;a1,…,ak,[b1;b2,…,bk]][a_0; a_1, \dots, a_k, b_0, b_1, \dots, b_k] = [a_0; a_1, \dots, a_k, [b_1; b_2, \dots, b_k]].

Let's denote Lk(x)=[ak;x]=ak+1x=ak⋅x+11⋅x+0L_{k}(x) = [a_k; x] = a_k + \frac{1}{x} = \frac{a_k\cdot x+1}{1\cdot x + 0}. Note that Lk(∞)=akL_k(\infty) = a_k. In this notion, it holds that

[a0;a1,…,ak,x]=[a0;[a1;[… ;[ak;x]]]]=(L0∘L1∘⋯∘Lk)(x)=pkx+pk−1qkx+qk−1.[a_0; a_1, \dots, a_k, x] = [a_0; [a_1; [\dots; [a_k; x]]]] = (L_0 \circ L_1 \circ \dots \circ L_k)(x) = \frac{p_k x + p_{k-1}}{q_k x + q_{k-1}}.

Thus, the problem boils down to the computation of

(Ll∘Ll+1∘⋯∘Lr)(∞).(L_l \circ L_{l+1} \circ \dots \circ L_r)(\infty).

Composition of transforms is associative, so it's possible to compute in each node of a segment tree the composition of transforms in its subtree.

Linear fractional transformation of a continued fraction

Let L(x)=ax+bcx+dL(x) = \frac{ax+b}{cx+d}. Compute the continued fraction representation [b0;b1,…,bm][b_0; b_1, \dots, b_m] of L(A)L(A) for A=[a0;a1,…,an]A=[a_0; a_1, \dots, a_n].

This allows to compute A+pq=qA+pqA + \frac{p}{q} = \frac{qA + p}{q} and A⋅pq=pAqA \cdot \frac{p}{q} = \frac{p A}{q} for any pq\frac{p}{q}.

Solution

As we noted above, [a0;a1,…,ak]=(La0∘La1∘⋯∘Lak)(∞)[a_0; a_1, \dots, a_k] = (L_{a_0} \circ L_{a_1} \circ \dots \circ L_{a_k})(\infty), hence L([a0;a1,…,ak])=(L∘La0∘La1∘…Lak)(∞)L([a_0; a_1, \dots, a_k]) = (L \circ L_{a_0} \circ L_{a_1} \circ \dots L_{a_k})(\infty).

Hence, by consequentially adding La0L_{a_0}, La1L_{a_1} and so on we would be able to compute

(L∘La0∘⋯∘Lak)(x)=L(pkx+pk−1qkx+qk−1)=akx+bkckx+dk.(L \circ L_{a_0} \circ \dots \circ L_{a_k})(x) = L\left(\frac{p_k x + p_{k-1}}{q_k x + q_{k-1}}\right)=\frac{a_k x + b_k}{c_k x + d_k}.

Since L(x)L(x) is invertible, it is also monotonous in xx. Therefore, for any x≥0x \geq 0 it holds that L(pkx+pk−1qkx+qk−1)L(\frac{p_k x + p_{k-1}}{q_k x + q_{k-1}}) is between L(pkqk)=akckL(\frac{p_k}{q_k}) = \frac{a_k}{c_k} and L(pk−1qk−1)=bkdkL(\frac{p_{k-1}}{q_{k-1}}) = \frac{b_k}{d_k}.

Moreover, for x=[ak+1;…,an]x=[a_{k+1}; \dots, a_n] it is equal to L(A)L(A). Hence, b0=⌊L(A)⌋b_0 = \lfloor L(A) \rfloor is between ⌊L(pkqk)⌋\lfloor L(\frac{p_k}{q_k}) \rfloor and ⌊L(pk−1qk−1)⌋\lfloor L(\frac{p_{k-1}}{q_{k-1}}) \rfloor. When they're equal, they're also equal to b0b_0.

Note that L(A)=(Lb0∘Lb1∘⋯∘Lbm)(∞)L(A) = (L_{b_0} \circ L_{b_1} \circ \dots \circ L_{b_m})(\infty). Knowing b0b_0, we can compose Lb0−1L_{b_0}^{-1} with the current transform and continue adding Lak+1L_{a_{k+1}}, Lak+2L_{a_{k+2}} and so on, looking for new floors to agree, from which we would be able to deduce b1b_1 and so on until we recover all values of [b0;b1,…,bm][b_0; b_1, \dots, b_m].

Continued fraction arithmetics

Let A=[a0;a1,…,an]A=[a_0; a_1, \dots, a_n] and B=[b0;b1,…,bm]B=[b_0; b_1, \dots, b_m]. Compute the continued fraction representations of A+BA+B and A⋅BA \cdot B.

Solution

Idea here is similar to the previous problem, but instead of L(x)=ax+bcx+dL(x) = \frac{ax+b}{cx+d} you should consider bilinear fractional transform L(x,y)=axy+bx+cy+dexy+fx+gy+hL(x, y) = \frac{axy+bx+cy+d}{exy+fx+gy+h}.

Rather than L(x)↦L(Lak(x))L(x) \mapsto L(L_{a_k}(x)) you would change your current transform as L(x,y)↦L(Lak(x),y)L(x, y) \mapsto L(L_{a_k}(x), y) or L(x,y)↦L(x,Lbk(y))L(x, y) \mapsto L(x, L_{b_k}(y)).

Then, you check if ⌊ae⌋=⌊bf⌋=⌊cg⌋=⌊dh⌋\lfloor \frac{a}{e} \rfloor = \lfloor \frac{b}{f} \rfloor = \lfloor \frac{c}{g} \rfloor = \lfloor \frac{d}{h} \rfloor and if they all agree, you use this value as ckc_k in the resulting fraction and change the transform as

L(x,y)↦1L(x,y)−ck.L(x, y) \mapsto \frac{1}{L(x, y) - c_k}.

Definition

A continued fraction x=[a0;a1,… ]x = [a_0; a_1, \dots] is said to be periodic if x=[a0;a1,…,ak,x]x = [a_0; a_1, \dots, a_k, x] for some kk.

A continued fraction x=[a0;a1,… ]x = [a_0; a_1, \dots] is said to be eventually periodic if x=[a0;a1,…,ak,y]x = [a_0; a_1, \dots, a_k, y], where yy is periodic.

For x=[1;1,1,… ]x = [1; 1, 1, \dots] it holds that x=1+1xx = 1 + \frac{1}{x}, thus x2=x+1x^2 = x + 1. There is a generic connection between periodic continued fractions and quadratic equations. Consider the following equation:

x=[a0;a1,…,ak,x].x = [a_0; a_1, \dots, a_k, x].

On one hand, this equation means that the continued fraction representation of xx is periodic with the period k+1k+1.

On the other hand, using the formula for convergents, this equation means that

x=pkx+pk−1qkx+qk−1.x = \frac{p_k x + p_{k-1}}{q_k x + q_{k-1}}.

That is, xx is a linear fractional transformation of itself. It follows from the equation that xx is a root of the second degree equation:

qkx2+(qk−1−pk)x−pk−1=0.q_k x^2 + (q_{k-1}-p_k)x - p_{k-1} = 0.

Similar reasoning stands for continued fractions that are eventually periodic, that is x=[a0;a1,…,ak,y]x = [a_0; a_1, \dots, a_k, y] for y=[b0;b1,…,bk,y]y=[b_0; b_1, \dots, b_k, y]. Indeed, from first equation we derive that x=L0(y)x = L_0(y) and from second equation that y=L1(y)y = L_1(y), where L0L_0 and L1L_1 are linear fractional transformations. Therefore,

x=(L0∘L1)(y)=(L0∘L1∘L0−1)(x).x = (L_0 \circ L_1)(y) = (L_0 \circ L_1 \circ L_0^{-1})(x).

One can further prove (and it was first done by Lagrange) that for arbitrary quadratic equation ax2+bx+c=0ax^2+bx+c=0 with integer coefficients, its solution xx is an eventually periodic continued fraction.

Quadratic irrationality

Find the continued fraction of α=x+ynz\alpha = \frac{x+y\sqrt{n}}{z} where x,y,z,n∈Zx, y, z, n \in \mathbb Z and n>0n > 0 is not a perfect square.

Solution

For the kk-th complete quotient sks_k of the number it generally holds that

α=[a0;a1,…,ak−1,sk]=skpk−1+pk−2skqk−1+qk−2.\alpha = [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}}.

Therefore,

sk=−αqk−1−pk−1αqk−pk=−qk−1yn+(xqk−1−zpk−1)qkyn+(xqk−zpk).s_k = -\frac{\alpha q_{k-1} - p_{k-1}}{\alpha q_k - p_k} = -\frac{q_{k-1} y \sqrt n + (x q_{k-1} - z p_{k-1})}{q_k y \sqrt n + (xq_k-zp_k)}.

Multiplying the numerator and denominator by (xqk−zpk)−qkyn(xq_k - zp_k) - q_k y \sqrt n, we'll get rid of n\sqrt n in the denominator, thus the complete quotients are of form

sk=xk+yknzk.s_k = \frac{x_k + y_k \sqrt n}{z_k}.

Let's find sk+1s_{k+1}, assuming that sks_k is known.

First of all, ak=⌊sk⌋=⌊xk+yk⌊n⌋zk⌋a_k = \lfloor s_k \rfloor = \left\lfloor \frac{x_k + y_k \lfloor \sqrt n \rfloor}{z_k} \right\rfloor. Then,

sk+1=1sk−ak=zk(xk−zkak)+ykn=zk(xk−ykak)−ykzkn(xk−ykak)2−yk2n.s_{k+1} = \frac{1}{s_k-a_k} = \frac{z_k}{(x_k - z_k a_k) + y_k \sqrt n} = \frac{z_k (x_k - y_k a_k) - y_k z_k \sqrt n}{(x_k - y_k a_k)^2 - y_k^2 n}.

Thus, if we denote tk=xk−ykakt_k = x_k - y_k a_k, it will hold that

xk+1=zktk,yk+1=−ykzk,zk+1=tk2−yk2n.\begin{align}x_{k+1} &=& z_k t_k, \\ y_{k+1} &=& -y_k z_k, \\ z_{k+1} &=& t_k^2 - y_k^2 n.\end{align}

Nice thing about such representation is that if we reduce xk+1,yk+1,zk+1x_{k+1}, y_{k+1}, z_{k+1} by their greatest common divisor, the result would be unique. Therefore, we may use it to check whether the current state has already been repeated and also to check where was the previous index that had this state.

Below is the code to compute the continued fraction representation for α=n\alpha = \sqrt n:

Python

text
# compute the continued fraction of sqrt(n)
def sqrt(n):
    n0 = math.floor(math.sqrt(n))
    x, y, z = 1, 0, 1
    a = []
    def step(x, y, z):
        a.append((x * n0 + y) // z)
        t = y - a[-1]*z
        x, y, z = -z*x, z*t, t**2 - n*x**2
        g = math.gcd(x, math.gcd(y, z))
        return x // g, y // g, z // g

    used = dict()
    for i in range(n):
        used[x, y, z] = i
        x, y, z = step(x, y, z)
        if (x, y, z) in used:
            return a

Using the same step function but different initial xx, yy and zz it is possible to compute it for arbitrary x+ynz\frac{x+y \sqrt{n}}{z}.

Tavrida NU Akai Contest - Continued Fraction

You're given xx and kk, xx is not a perfect square. Let x=[a0;a1,… ]\sqrt x = [a_0; a_1, \dots], find pkqk=[a0;a1,…,ak]\frac{p_k}{q_k}=[a_0; a_1, \dots, a_k] for 0≤k≤1090 \leq k \leq 10^9.

Solution

After computing the period of x\sqrt x, it is possible to compute aka_k using binary exponentiation on the linear fractional transformation induced by the continued fraction representation. To find the resulting transformation, you compress the period of size TT into a single transformation and repeat it ⌊k−1T⌋\lfloor \frac{k-1}{T}\rfloor times, after which you manually combine it with the remaining transformations.

Python

text
x, k = map(int, input().split())

mod = 10**9+7

# compose (A[0]*x + A[1]) / (A[2]*x + A[3]) and (B[0]*x + B[1]) / (B[2]*x + B[3])
def combine(A, B):
    return [t % mod for t in [A[0]*B[0]+A[1]*B[2], A[0]*B[1]+A[1]*B[3], A[2]*B[0]+A[3]*B[2], A[2]*B[1]+A[3]*B[3]]]

A = [1, 0, 0, 1] # (x + 0) / (0*x + 1) = x

a = sqrt(x)

T = len(a) - 1 # period of a

# apply ak + 1/x = (ak*x+1)/(1x+0) to (Ax + B) / (Cx + D)
for i in reversed(range(1, len(a))):
    A = combine([a[i], 1, 1, 0], A)

def bpow(A, n):
    return [1, 0, 0, 1] if not n else combine(A, bpow(A, n-1)) if n % 2 else bpow(combine(A, A), n // 2)


C = (0, 1, 0, 0) # = 1 / 0
while k % T:
    i = k % T
    C = combine([a[i], 1, 1, 0], C)
    k -= 1

C = combine(bpow(A, k // T), C)
C = combine([a[0], 1, 1, 0], C)
print(str(C[1]) + '/' + str(C[3]))

Geometric interpretation

Let r⃗k=(qk;pk)\vec r_k = (q_k;p_k) for the convergent rk=pkqkr_k = \frac{p_k}{q_k}. Then, the following recurrence holds:

r⃗k=akr⃗k−1+r⃗k−2.\vec r_k = a_k \vec r_{k-1} + \vec r_{k-2}.

Let r⃗=(1;r)\vec r = (1;r). Then, each vector (x;y)(x;y) corresponds to the number that is equal to its slope coefficient yx\frac{y}{x}.

With the notion of pseudoscalar product (x1;y1)×(x2;y2)=x1y2−x2y1(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

sk=−r⃗k−2×r⃗r⃗k−1×r⃗=∣r⃗k−2×r⃗r⃗k−1×r⃗∣.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|.

The last equation is due to the fact that rk−1r_{k-1} and rk−2r_{k-2} lie on the different sides of rr, thus pseudoscalar products of r⃗k−1\vec r_{k-1} and r⃗k−2\vec r_{k-2} with r⃗\vec r have distinct signs. With ak=⌊sk⌋a_k = \lfloor s_k \rfloor in mind, formula for r⃗k\vec r_k now looks like

r⃗k=r⃗k−2+⌊∣r⃗×r⃗k−2r⃗×r⃗k−1∣⌋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}.

Note that r⃗k×r=(q;p)×(1;r)=qr−p\vec r_k \times r = (q;p) \times (1;r) = qr - p, thus

ak=⌊∣qk−1r−pk−1qk−2r−pk−2∣⌋.a_k = \left\lfloor \left| \frac{q_{k-1}r-p_{k-1}}{q_{k-2}r-p_{k-2}} \right| \right\rfloor.
Explanation

As we have already noted, ak=⌊sk⌋a_k = \lfloor s_k \rfloor, where sk=[ak;ak+1,ak+2,… ]s_k = [a_k; a_{k+1}, a_{k+2}, \dots]. On the other hand, from the convergent recurrence we derive that

r=[a0;a1,…,ak−1,sk]=skpk−1+pk−2skqk−1+qk−2.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}}.

In vector form, it rewrites as

r⃗∥skr⃗k−1+r⃗k−2,\vec r \parallel s_k \vec r_{k-1} + \vec r_{k-2},

meaning that r⃗\vec r and skr⃗k−1+r⃗k−2s_k \vec r_{k-1} + \vec r_{k-2} are collinear (that is, have the same slope coefficient). Taking the pseudoscalar product of both parts with r⃗\vec r, we get

0=sk(r⃗k−1×r⃗)+(r⃗k−2×r⃗),0 = s_k (\vec r_{k-1} \times \vec r) + (\vec r_{k-2} \times \vec r),

which yields the final formula

sk=−r⃗k−2×r⃗r⃗k−1×r⃗.s_k = -\frac{\vec r_{k-2} \times \vec r}{\vec r_{k-1} \times \vec r}.

Nose stretching algorithm

Each time you add r⃗k−1\vec r_{k-1} to the vector p⃗\vec p, the value of p⃗×r⃗\vec p \times \vec r is increased by r⃗k−1×r⃗\vec r_{k-1} \times \vec r.

Thus, ak=⌊sk⌋a_k=\lfloor s_k \rfloor is the maximum integer number of r⃗k−1\vec r_{k-1} vectors that can be added to r⃗k−2\vec r_{k-2} without changing the sign of the cross product with r⃗\vec r.

In other words, aka_k is the maximum integer number of times you can add r⃗k−1\vec r_{k-1} to r⃗k−2\vec r_{k-2} without crossing the line defined by r⃗\vec r:

Convergents of r=79=[0;1,3,2]r=\frac{7}{9}=[0;1,3,2]. Semiconvergents correspond to intermediate points between gray arrows.

On the picture above, r⃗2=(4;3)\vec r_2 = (4;3) is obtained by repeatedly adding r⃗1=(1;1)\vec r_1 = (1;1) to r⃗0=(1;0)\vec r_0 = (1;0).

When it is not possible to further add r⃗1\vec r_1 to r⃗0\vec r_0 without crossing the y=rxy=rx line, we go to the other side and repeatedly add r⃗2\vec r_2 to r⃗1\vec r_1 to obtain r⃗3=(9;7)\vec r_3 = (9;7).

This procedure generates exponentially longer vectors, that approach the line.

For this property, the procedure of generating consequent convergent vectors was dubbed the nose stretching algorithm by Boris Delaunay.

If we look on the triangle drawn on points r⃗k−2\vec r_{k-2}, r⃗k\vec r_{k} and 0⃗\vec 0 we will notice that its doubled area is

∣r⃗k−2×r⃗k∣=∣r⃗k−2×(r⃗k−2+akr⃗k−1)∣=ak∣r⃗k−2×r⃗k−1∣=ak.|\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.

Combined with the Pick's theorem, it means that there are no lattice points strictly inside the triangle and the only lattice points on its border are 0⃗\vec 0 and r⃗k−2+t⋅r⃗k−1\vec r_{k-2} + t \cdot \vec r_{k-1} for all integer tt such that 0≤t≤ak0 \leq t \leq a_k. When joined for all possible kk 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 r⃗k\vec r_k with odd coefficients form a convex hull of lattice points with x≥0x \geq 0 above the line y=rxy=rx, while r⃗k\vec r_k with even coefficients form a convex hull of lattice points with x>0x > 0 below the line y=rxy=rx.

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

Now that the most important facts and concepts were introduced, it is time to delve into specific problem examples.

Convex hull under the line

Find the convex hull of lattice points (x;y)(x;y) such that 0≤x≤N0 \leq x \leq N and 0≤y≤rx0 \leq y \leq rx for r=[a0;a1,…,ak]=pkqkr=[a_0;a_1,\dots,a_k]=\frac{p_k}{q_k}.

Solution

If we were considering the unbounded set 0≤x0 \leq x, the upper convex hull would be given by the line y=rxy=rx itself.

However, with additional constraint x≤Nx \leq N we'd need to eventually deviate from the line to maintain proper convex hull.

Let t=⌊Nqk⌋t = \lfloor \frac{N}{q_k}\rfloor, then first tt lattice points on the hull after (0;0)(0;0) are α⋅(qk;pk)\alpha \cdot (q_k; p_k) for integer 1≤α≤t1 \leq \alpha \leq t.

However (t+1)(qk;pk)(t+1)(q_k; p_k) can't be next lattice point since (t+1)qk(t+1)q_k is greater than NN.

To get to the next lattice points in the hull, we should get to the point (x;y)(x;y) which diverges from y=rxy=rx by the smallest margin, while maintaining x≤Nx \leq N.

Convex hull of lattice points under y=47xy=\frac{4}{7}x for 0≤x≤190 \leq x \leq 19 consists of points (0;0),(7;4),(14;8),(16;9),(18;10),(19;10)(0;0), (7;4), (14;8), (16;9), (18;10), (19;10).

Let (x;y)(x; y) be the last current point in the convex hull. Then the next point (x′;y′)(x'; y') is such that x′≤Nx' \leq N and (x′;y′)−(x;y)=(Δx;Δy)(x'; y') - (x; y) = (\Delta x; \Delta y) is as close to the line y=rxy=rx as possible. In other words, (Δx;Δy)(\Delta x; \Delta y) maximizes rΔx−Δyr \Delta x - \Delta y subject to Δx≤N−x\Delta x \leq N - x and Δy≤rΔx\Delta y \leq r \Delta x.

Points like that lie on the convex hull of lattice points below y=rxy=rx. In other words, (Δx;Δy)(\Delta x; \Delta y) must be a lower semiconvergent of rr.

That being said, (Δx;Δy)(\Delta x; \Delta y) is of form (qi−1;pi−1)+t⋅(qi;pi)(q_{i-1}; p_{i-1}) + t \cdot (q_i; p_i) for some odd number ii and 0≤t<ai0 \leq t < a_i.

To find such ii, we can traverse all possible ii starting from the largest one and use t=⌊N−x−qi−1qi⌋t = \lfloor \frac{N-x-q_{i-1}}{q_i} \rfloor for ii such that N−x−qi−1≥0N-x-q_{i-1} \geq 0.

With (Δx;Δy)=(qi−1;pi−1)+t⋅(qi;pi)(\Delta x; \Delta y) = (q_{i-1}; p_{i-1}) + t \cdot (q_i; p_i), the condition Δy≤rΔx\Delta y \leq r \Delta x would be preserved by semiconvergent properties.

And t<ait < a_i would hold because we already exhausted semiconvergents obtained from i+2i+2, hence x+qi−1+aiqi=x+qi+1x + q_{i-1} + a_i q_i = x+q_{i+1} is greater than NN.

Now that we may add (Δx;Δy)(\Delta x; \Delta y), to (x;y)(x;y) for k=⌊N−xΔx⌋k = \lfloor \frac{N-x}{\Delta x} \rfloor times before we exceed NN, after which we would try the next semiconvergent.

C++Python

text
// 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);
}
text
# 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

Timus - Crime and Punishment

You're given integer numbers AA, BB and NN. Find x≥0x \geq 0 and y≥0y \geq 0 such that Ax+By≤NAx + By \leq N and Ax+ByAx + By is the maximum possible.

Solution

In this problem it holds that 1≤A,B,N≤2⋅1091 \leq A, B, N \leq 2 \cdot 10^9, so it can be solved in O(N)O(\sqrt N). However, there is O(log⁡N)O(\log N) solution with continued fractions.

For our convenience, we will invert the direction of xx by doing a substitution x↦⌊NA⌋−xx \mapsto \lfloor \frac{N}{A}\rfloor - x, so that now we need to find the point (x;y)(x; y) such that 0≤x≤⌊NA⌋0 \leq x \leq \lfloor \frac{N}{A} \rfloor, By−Ax≤N   mod   ABy - Ax \leq N \;\bmod\; A and By−AxBy - Ax is the maximum possible. Optimal yy for each xx has a value of ⌊Ax+(N mod A)B⌋\lfloor \frac{Ax + (N \bmod A)}{B} \rfloor.

To treat it more generically, we will write a function that finds the best point on 0≤x≤N0 \leq x \leq N and y=⌊Ax+BC⌋y = \lfloor \frac{Ax+B}{C} \rfloor.

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≤Nx \leq N. Unfortunately, unlike the previous problem, you need to make sure that you don't cross the y=Ax+BCy=\frac{Ax+B}{C} line while getting closer to it, so you should keep it in mind when calculating semiconvergent's coefficient tt.

Python

text
# (x, y) such that y = (A*x+B) // C,
# Cy - Ax is max and 0 <= x <= N.
def closest(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 = closest(A, N % A, B, N // A)
    return N // A - x, y

June Challenge 2017 - Euler Sum

Compute ∑x=1N⌊ex⌋\sum\limits_{x=1}^N \lfloor ex \rfloor, where e=[2;1,2,1,1,4,1,1,6,1,…,1,2n,1,… ]e = [2; 1, 2, 1, 1, 4, 1, 1, 6, 1, \dots, 1, 2n, 1, \dots] is the Euler's number and N≤104000N \leq 10^{4000}.

Solution

This sum is equal to the number of lattice point (x;y)(x;y) such that 1≤x≤N1 \leq x \leq N and 1≤y≤ex1 \leq y \leq ex.

After constructing the convex hull of the points below y=exy=ex, this number can be computed using Pick's theorem:

C++Python

text
// 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;
}
text
# 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

NAIPC 2019 - It's a Mod, Mod, Mod, Mod World

Given pp, qq and nn, compute ∑i=1n[p⋅i mod q]\sum\limits_{i=1}^n [p \cdot i \bmod q].

Solution

This problem reduces to the previous one if you note that a mod b=a−⌊ab⌋ba \bmod b = a - \lfloor \frac{a}{b} \rfloor b. With this fact, the sum reduces to

∑i=1n(p⋅i−⌊p⋅iq⌋q)=pn(n+1)2−q∑i=1n⌊p⋅iq⌋.\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 ⌊rx⌋\lfloor rx \rfloor for xx from 11 to NN is something that we're capable of from the previous problem.

C++Python

text
void solve(int p, int q, int N) {
    cout << p * N * (N + 1) / 2 - q * sum_floor(fraction(p, q), N) << "\n";
}
text
def solve(p, q, N):
    return p * N * (N + 1) // 2 - q * sum_floor(fraction(p, q), N)

Library Checker - Sum of Floor of Linear

Given NN, MM, AA and BB, compute ∑i=0N−1⌊A⋅i+BM⌋\sum\limits_{i=0}^{N-1} \lfloor \frac{A \cdot i + B}{M} \rfloor.

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=Ax+BMy = \frac{Ax+B}{M}.

We already know how to solve it for B=0B = 0. Moreover, we already know how to construct this convex hull up to the closest lattice point to this line on [0,N−1][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][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=Ax+BMy=\frac{Ax+B}{M} on [0,N−1][0, N-1], we can construct it up to the closest point to the line on [0,N−1][0, N-1] and then continue as if the line passes through this point, reusing algorithm for constructing convex hull with B=0B=0:

Python

text
# 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

OKC 2 - From Modular to Rational

There is a rational number pq\frac{p}{q} such that 1≤p,q≤1091 \leq p, q \leq 10^9. You may ask the value of pq−1p q^{-1} modulo m∼109m \sim 10^9 for several prime numbers mm. Recover pq\frac{p}{q}.

Equivalent formulation: Find xx that delivers the minimum of Ax   mod   MAx \;\bmod\; M for 1≤x≤N1 \leq x \leq N.

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 mm.

There could be several possible solutions (p,q)(p, q) to p≡qr(modm)p \equiv qr \pmod m for a given remainder rr. However, if (p1,q1)(p_1, q_1) and (p2,q2)(p_2, q_2) are both the solutions then it also holds that p1q2≡p2q1(modm)p_1 q_2 \equiv p_2 q_1 \pmod m. Assuming that p1q1≠p2q2\frac{p_1}{q_1} \neq \frac{p_2}{q_2} it means that ∣p1q2−p2q1∣|p_1 q_2 - p_2 q_1| is at least mm.

In the statement we were told that 1≤p,q≤1091 \leq p, q \leq 10^9, so if both p1,q1p_1, q_1 and p2,q2p_2, q_2 are at most 10910^9, then the difference is at most 101810^{18}. For m>1018m > 10^{18} it means that the solution pq\frac{p}{q} with 1≤p,q≤1091 \leq p, q \leq 10^9 is unique, as a rational number.

So, the problem boils down, given rr modulo mm, to finding any qq such that 1≤q≤1091 \leq q \leq 10^9 and qr   mod   m≤109qr \;\bmod\; m \leq 10^9.

This is effectively the same as finding qq that delivers the minimum possible qr mod mqr \bmod m for 1≤q≤1091 \leq q \leq 10^9.

For qr=km+bqr = km + b it means that we need to find a pair (q,m)(q, m) such that 1≤q≤1091 \leq q \leq 10^9 and qr−km≥0qr - km \geq 0 is the minimum possible.

Since mm is constant, we can divide by it and further restate it as find qq such that 1≤q≤1091 \leq q \leq 10^9 and rmq−k≥0\frac{r}{m} q - k \geq 0 is the minimum possible.

In terms of continued fractions it means that kq\frac{k}{q} is the best diophantine approximation to rm\frac{r}{m} and it is sufficient to only check lower semiconvergents of rm\frac{r}{m}.

Python

text
# 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]

Practice problems