Continued fraction

Introduction

Continued fractions can represent a real number as the limit of a convergent sequence of rational numbers. The rational numbers in this sequence are easy to compute and provide the best approximations to the real number, so continued fractions are often used in algorithmic competitions. In addition, continued fractions are closely related to the Euclidean algorithm and can therefore be applied to a series of number-theoretic problems.

Implementing continued-fraction algorithms

This article provides implementations of a series of continued-fraction algorithms. Some algorithms may not guarantee that the integers involved in intermediate computations fit within 32-bit or 64-bit integer variables. In such cases, refer to the corresponding Python implementation, or replace the integer variables in the C++ implementation with a big integer class. To keep the focus on the main ideas, some code in this article may call functions implemented earlier without repeating their implementations.

Continued fractions

A continued fraction (continued fraction) is, in itself, only a form of notation.

Finite continued fractions

For a sequence {ak}i=0n\{a_k\}_{i=0}^n, the continued fraction [a0,a1,⋯ ,an][a_0,a_1,\cdots,a_n] denotes the expansion

x=a0+1a1+1a2+1⋯+1an.x = a_0+\dfrac{1}{a_1+\dfrac{1}{a_2+\dfrac{1}{\cdots+\dfrac{1}{a_n}}}}.

A continued fraction is meaningful if and only if the corresponding expansion is meaningful. These aka_k are called the terms or coefficients of the continued fraction.

Notation

More general continued fractions allow the numerators in the expansion to be other than 11, which requires modifying the notation accordingly; this is beyond the scope of this article. In addition, some literature writes the first comma “,,” as a semicolon “;;”; this has no difference in meaning from the notation used here.

Of course, continued fractions can also be generalized to infinite sequences.

Infinite continued fractions

For an infinite sequence {ak}i=0∞\{a_k\}_{i=0}^\infty, the continued fraction [a0,a1,⋯ ][a_0,a_1,\cdots] denotes the limit

x=lim⁡k→∞xk=lim⁡k→∞[a0,a1,⋯ ,ak].x = \lim_{k\rightarrow\infty} x_k = \lim_{k\rightarrow\infty} [a_0,a_1,\cdots,a_k].

A continued fraction is meaningful if and only if the corresponding limit is meaningful. Here, xk=[a0,a1,⋯ ,ak]x_k=[a_0,a_1,\cdots,a_k] is called the convergent of xx with index kk, while rk=[ak,ak+1,⋯ ]r_k=[a_k,a_{k+1},\cdots] is called the remainder or complete quotient of xx with index kk. Accordingly, the term aka_k is sometimes called the kk-th partial quotient.

Simple continued fractions

In number theory, we mainly consider the case where all terms of a continued fraction are integers.

Simple continued fractions

For a continued fraction [a0,a1,⋯ ][a_0,a_1,\cdots], if a0a_0 is an integer and a1,a2,⋯a_1,a_2,\cdots are all positive integers, it is called a simple continued fraction, also abbreviated as a continued fraction. If the sequence {ai}\{a_i\} is finite, it is called a finite (simple) continued fraction; otherwise, it is called an infinite (simple) continued fraction. In addition, a0a_0 is called its integer part.

Unless otherwise stated, every continued fraction mentioned in this article means a simple continued fraction. It can be proved that every infinite simple continued fraction converges, and its remainders are always positive.

Continued fractions have the following basic properties:

Properties

Let x=[a0,a1,a2,⋯ ]x=[a_0,a_1,a_2,\cdots] be a real number. Then the following properties hold:

  1. For any k∈Zk\in\mathbf Z, x+k=[a0+k,a1,a2,⋯ ]x+k=[a_0+k,a_1,a_2,\cdots];
  2. For a real number x>1x>1, a0>0a_0>0, and its reciprocal is x−1=[0,a0,a1,a2,⋯ ]x^{-1}=[0,a_0,a_1,a_2,\cdots].

Finite continued fractions correspond to rational numbers. Every rational number has exactly two representations as a continued fraction, whose lengths necessarily have opposite parity. The only difference between the two representations is whether the last term is 11, namely

x=[a0,a1,⋯ ,an]=[a0,a1,⋯ ,an−1,1].x = [a_0,a_1,\cdots,a_n] = [a_0,a_1,\cdots,a_n-1,1].

These two continued fractions are called the continued fraction representations of the rational number xx. The one whose final term is not one is called the standard representation, and the one whose final term is one is called the nonstandard representation.1

Example

The continued fraction representations of the rational number x=53x=\dfrac{5}{3} are

x=[1,1,1,1]=1+11+11+11,x=[1,1,2]=1+11+12.\begin{aligned} x = [1,1,1,1] &= 1+\dfrac{1}{1+\dfrac{1}{1+\dfrac{1}{1}}},\\ x = [1,1,2] &= 1+\dfrac{1}{1+\dfrac{1}{2}}. \end{aligned}

Infinite continued fractions correspond to irrational numbers. Moreover, every irrational number has exactly one representation as a continued fraction, called its continued fraction representation.

Finding a continued-fraction representation

To find the continued fraction representation of a real number xx, observe that if its remainder rkr_k is not an integer, then it necessarily satisfies

rk=[ak,ak+1,⋯ ]=[ak,rk+1]=ak+1rk+1.r_k = [a_k,a_{k+1},\cdots] = [a_k,r_{k+1}] = a_k + \dfrac{1}{r_{k+1}}.

Also, rk+1>1r_{k+1}>1. Therefore, starting from r0=xr_0=x, we can recursively compute

ak=⌊rk⌋, rk+1=1rk−ak.a_k = \lfloor r_k\rfloor,\ r_{k+1} = \dfrac{1}{r_k-a_k}.

The sequence {ak}\{a_k\} produced by this process is always uniquely determined, unless some remainder rkr_k becomes an integer. If rkr_k is an integer, the process should terminate, and we may choose to output either the corresponding standard or nonstandard representation.

In algorithmic competitions, we often handle rational numbers x=pqx=\dfrac{p}{q}. Here, every remainder rkr_k is a rational number pkqk\dfrac{p_k}{q_k}, and for k>0k>0, since rk>1r_k>1, we always have pk>qkp_k>q_k. Computing the recurrence above gives

ak=⌊pkqk⌋, rk+1=1rk−ak=qkpk−akqk=qkpk mod qk.a_k = \left\lfloor\frac{p_k}{q_k}\right\rfloor,\ r_{k+1} = \dfrac{1}{r_k-a_k} = \dfrac{q_k}{p_k-a_kq_k} = \dfrac{q_k}{p_k\bmod q_k}.

The computation is in fact applied to pp and qq using the Euclidean algorithm. This also shows that for a rational number r=pqr=\dfrac{p}{q}, the length of its continued fraction representation is O(log⁡min⁡{p,q})O(\log\min\{p, q\}), and the complexity of computing the continued fraction of pq\dfrac{p}{q} is also O(log⁡min⁡{p,q})O(\log\min\{p, q\}).

Reference implementation

Given the numerator pp and denominator qq of a fraction, output the coefficient sequence [a0,a1,⋯ ,an][a_0,a_1,\cdots,a_n] of its continued fraction.

C++

// Find the continued fraction representation of P/Q.
auto fraction(int p, int q) {
  std::vector<int> a;
  while (q) {
    a.push_back(p / q);
    std::tie(p, q) = std::make_pair(q, p % q);
  }
  return a;
}

Python

# Find the continued fraction representation of P/Q.
def fraction(p, q):
    a = []
    while q:
        a.append(p // q)
        p, q = q, p % q
    return a

Convergents

The concept of convergents was introduced in the definition of continued fractions. For a real number xx, retaining the first kk terms of its continued fraction representation gives the continued fraction xkx_k, which is called a convergent of xx with index kk. Every convergent of xx, including xkx_k, is rational, and the sequence {xk}\{x_k\} converges to xx.

Example: convergents of the golden ratio

The first few convergents of the continued fraction x=[1,1,1,1,⋯ ]x=[1,1,1,1,\cdots] are

x0=[1]=1,x1=[1,1]=2,x2=[1,1,1]=32,x3=[1,1,1,1]=53,x4=[1,1,1,1,1]=85.\begin{aligned} x_0 &= [1]=1,\\ x_1 &= [1,1]=2,\\ x_2 &= [1,1,1]=\dfrac{3}{2},\\ x_3 &= [1,1,1,1]=\dfrac{5}{3},\\ x_4 &= [1,1,1,1,1]=\dfrac{8}{5}. \end{aligned}

By induction, we can prove

xk=Fk+2Fk+1,x_k = \frac{F_{k+2}}{F_{k+1}},

where {Fk}\{F_k\} is the Fibonacci sequence. Its closed form gives

xk=ϕk+2−(−ϕ)−(k+2)ϕk+1−(−ϕ)−(k+1),x_k = \frac{\phi^{k+2}-(-\phi)^{-(k+2)}}{\phi^{k+1}-(-\phi)^{-(k+1)}},

where ϕ=1+52\phi=\dfrac{1+\sqrt{5}}{2} is the golden ratio. As kk tends to infinity,

x=lim⁡k→∞xk=ϕ.x=\lim_{k\rightarrow\infty}x_k=\phi.

Therefore, the continued fraction x=[1,1,1,1,⋯ ]x=[1,1,1,1,\cdots] represents the golden ratio ϕ\phi.

These convergents approach the corresponding real number, so they can be used to approximate it. For this purpose, we need to understand the properties of convergents.

Recurrence

First, we need to solve the problem of computing these convergents. Although a convergent is obtained by appending one term to the continued fraction, it is not necessary to recompute its value each time. In fact, convergents satisfy the following recurrence:

Recurrence formula

For a continued fraction x=[a0,a1,a2,⋯ ]x=[a_0,a_1,a_2,\cdots], suppose its kk-th convergent xkx_k can be written as the fraction pkqk\dfrac{p_k}{q_k}. Then

pk=akpk−1+pk−2,qk=akqk−1+qk−2.\begin{aligned} p_k &= a_kp_{k-1}+p_{k-2},\\ q_k &= a_kq_{k-1}+q_{k-2}. \end{aligned}

The recurrence starts from the (formal) fractions

x−1=p−1q−1=10, x−2=p−2q−2=01.x_{-1}=\frac{p_{-1}}{q_{-1}}=\frac{1}{0},\ x_{-2}=\frac{p_{-2}}{q_{-2}}=\frac{0}{1}.
Proof

The numerator and denominator of the convergent xkx_k can be viewed as multivariate polynomials in a0,a1,⋯ ,aka_0, a_1, \cdots, a_k:

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

By the definition of a convergent,

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,\cdots, a_k]}= a_0 + \frac{Q_{k-1}(a_1, \cdots, a_k)}{P_{k-1}(a_1, \cdots, a_k)} = \frac{a_0 P_{k-1}(a_1, \dots, a_k) + Q_{k-1}(a_1, \cdots, a_k)}{P_{k-1}(a_1, \cdots, a_k)}.

Comparing this with the preceding expression, set Qk(a0,⋯ ,ak)=Pk−1(a1,⋯ ,ak)Q_k(a_0, \cdots, a_k) = P_{k-1}(a_1, \cdots, a_k) without loss of generality. Then the convergent can be written as

rk=Pk(a0,a1,⋯ ,ak)Pk−1(a1,⋯ ,ak)r_k = \frac{P_k(a_0, a_1, \cdots, a_k)}{P_{k-1}(a_1, \cdots, a_k)}

and the polynomial PkP_k satisfies the recurrence

Pk(a0,⋯ ,ak)=a0Pk−1(a1,⋯ ,ak)+Pk−2(a2,⋯ ,ak).P_k(a_0, \cdots, a_k) = a_0 P_{k-1}(a_1, \cdots, a_k) + P_{k-2}(a_2, \cdots, a_k).

Since

r0=a0, r1=a0+1a1=a0a1+1a1,r_0 = a_0,\ r_1 = a_0+\dfrac{1}{a_1} = \frac{a_0a_1+1}{a_1},

the starting values are

P0(a0)=a0, P1(a0,a1)=a0a1+1.P_0(a_0) = a_0,\ P_1(a_0,a_1) = a_0a_1 + 1.

If we set

P−1=1, P−2=0,P_{-1} = 1,\ P_{-2} = 0,

it can be verified that the recurrence also holds for k=0,1k=0,1. This is equivalent to defining the formal fractions r−1=10r_{-1}=\dfrac{1}{0} and r−2=01r_{-2}=\dfrac{0}{1}.

The polynomial sequence PkP_k satisfying the recurrence above is called the continuant2. It can be written in determinant form:

Pk(a0,⋯ ,ak)=det⁡(a010⋯0−1a11⋱⋮0−1a2⋱0⋮⋱⋱⋱10⋯0−1ak).P_k(a_0,\cdots,a_k)=\det \begin{pmatrix} a_0 & 1 & 0 & \cdots & 0 \\ -1 & a_1 & 1 & \ddots & \vdots \\ 0 & -1 & a_2 & \ddots & 0 \\ \vdots & \ddots & \ddots & \ddots & 1 \\ 0 & \cdots & 0 & -1 & a_k \end{pmatrix}.

This is the determinant of a tridiagonal matrix. Expanding from the upper-left corner verifies that it satisfies the recurrence and initial conditions above. Conversely, expanding from the lower-right corner gives the recurrence

Pk(a0,⋯ ,ak)=akPk−1(a0,⋯ ,ak−1)+Pk−2(a0,⋯ ,ak−2),P_k(a_0, \cdots, a_k) = a_k P_{k-1}(a_0, \cdots, a_{k-1}) + P_{k-2}(a_0, \cdots, a_{k-2}),

which is what we needed to prove.

Notation

When this article writes the convergent xkx_k as pkqk\dfrac{p_k}{q_k}, it always means that the numerator pkp_k and denominator qkq_k are given by the recurrence above. We will show below that this always produces the reduced form of the convergent.

The recurrence shows that

xk=akpk−1+pk−2akqk−1+qk−2x_k=\dfrac{a_kp_{k-1}+p_{k-2}}{a_kq_{k-1}+q_{k-2}}

lies between xk−1x_{k-1} and xk−2x_{k-2}.

As corollaries of the recurrence for convergents, we have the following reversal and reciprocal theorems:

Reversal theorem

Suppose the real number x=[a0,a1,a2,⋯ ]x=[a_0,a_1,a_2,\cdots] has a convergent with index kk, namely pkqk\dfrac{p_k}{q_k}. Then the ratios of the numerators and denominators of two adjacent convergents are respectively

pkpk−1=[ak,ak−1,⋯ ,a1,a0],qkqk−1=[ak,ak−1,⋯ ,a1].\begin{aligned} \frac{p_k}{p_{k-1}}&=[a_k,a_{k-1},\cdots,a_1,a_0],\\ \frac{q_k}{q_{k-1}}&=[a_k,a_{k-1},\cdots,a_1]. \end{aligned}

If a0=0a_0=0=0, interpret the first continued fraction as truncated at the penultimate term, namely [ak,ak−1,⋯ ,a2][a_k,a_{k-1},\cdots,a_2].

Proof

Dividing the two sides of the recurrences for pkp_k and qkq_k by pk−1p_{k-1} and qk−1q_{k-1} respectively gives

pkpk−1=ak+pk−2pk−1,qkqk−1=ak+qk−2qk−1.\begin{aligned} \frac{p_k}{p_{k-1}} &= a_k + \frac{p_{k-2}}{p_{k-1}},\\ \frac{q_k}{q_{k-1}} &= a_k + \frac{q_{k-2}}{q_{k-1}}. \end{aligned}

Iterating these two equations gives two continued fractions. Substituting the initial values p0p−1=a0\dfrac{p_0}{p_{-1}}=a_0 and q1q0=a1\dfrac{q_1}{q_0}=a_1 completes the result. When a0=0a_0=0, interpret the resulting continued fraction as a formal expression; its remainder is

[a2,a1,0]=a2+1a1+10=a2+00a1+1=a2.[a_2,a_1,0]=a_2+\dfrac{1}{a_1+\dfrac{1}{0}}=a_2+\dfrac{0}{0a_1+1}=a_2.

Thus, the last two terms can be omitted directly. For a rigorous proof, simply observe that this expression can be regarded as the limit as a0→0a_0\rightarrow 0.

Reciprocal theorem

The reciprocal of a convergent of a real number x>0x>0 is a convergent of x−1x^{-1}.

Proof

Without loss of generality, let x>1x>1 and let its continued fraction representation be [a0,a1,a2,⋯ ][a_0,a_1,a_2,\cdots]. Then the continued fraction representation of x−1x^{-1} is [0,a0,a1,a2,⋯ ][0,a_0,a_1,a_2,\cdots]. Their convergents can be obtained from the recurrence. For xx, the initial conditions are x−2=01x_{-2}=\dfrac{0}{1} and x−1=10x_{-1}=\dfrac{1}{0}; for y=x−1y=x^{-1}, the initial conditions are y−1=10y_{-1}=\dfrac{1}{0} and y0=01y_{0}=\dfrac{0}{1}. Therefore, x−2=(y−1)−1x_{-2}=(y_{-1})^{-1} and x−1=(y0)−1x_{-1}=(y_0)^{-1}. The recurrence gives xk=yk+1−1x_k=y_{k+1}^{-1}. This shows that the reciprocals of the convergents of xx are convergents of y=x−1y=x^{-1}. The case 0<x≤10<x\le 1 can be discussed similarly.

Using the recurrence obtained in this section, we get the following algorithm for computing convergents:

Reference implementation

Given the coefficients a0,a1,⋯ ,ana_0,a_1,\cdots,a_n of a continued fraction, find the sequences of numerators and denominators (p0,q0),(p1,q1),⋯ ,(pn,qn)(p_0,q_0),(p_1,q_1),\cdots,(p_n,q_n) of its convergents.

C++

// Find the convergents of a continued fraction A.
// Numerators and denominators stored separately in P and Q.
auto convergents(std::vector<int> a) {
  std::vector<int> p = {0, 1};
  std::vector<int> q = {1, 0};
  for (auto it : a) {
    p.push_back(p.back() * it + p.end()[-2]);
    q.push_back(q.back() * it + q.end()[-2]);
  }
  return std::make_pair(p, q);
}

Python

# Find the convergents of a continued fraction A.
# Numerators and denominators stored separately in P and Q.
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

Error estimates

Using the recurrence for convergents, we can estimate the error produced when using a convergent to approximate a real number.

First, we can compute the difference between adjacent convergents:

Difference of convergents

Let xk=pkqkx_k=\dfrac{p_k}{q_k} be a convergent of the real number xx with index kk. Then

pk+1qk−pkqk+1=(−1)k.p_{k+1}q_k − p_kq_{k+1} = (−1)^k.

Therefore, the difference between two adjacent convergents is

xk+1−xk=(−1)kqk+1qk.x_{k+1} - x_k = \dfrac{(-1)^k}{q_{k+1}q_k}.
Proof

By the recurrence,

det⁡(pk+1pkqk+1qk)=det⁡(ak+1pk+pk−1pkak+1qk+qk−1qk)=det⁡(pk−1pkqk−1qk)=−det⁡(pkpk−1qkqk−1)=(−1)k+2det⁡(1001)=(−1)k.\begin{aligned} \det\begin{pmatrix} p_{k+1} & p_k \\ q_{k+1} & q_k \end{pmatrix} &= \det\begin{pmatrix} a_{k+1}p_{k}+p_{k-1} & p_k \\ a_{k+1}q_{k}+q_{k-1} & q_k \end{pmatrix} = \det\begin{pmatrix} p_{k-1} & p_k\\ q_{k-1} & q_k \end{pmatrix} \\ &= - \det\begin{pmatrix} p_k & p_{k-1}\\ q_k & q_{k-1} \end{pmatrix} = (-1)^{k+2} \det\begin{pmatrix} 1 & 0\\ 0 & 1 \end{pmatrix} =(-1)^k. \end{aligned}

This is exactly pk+1qk−pkqk+1=(−1)kp_{k+1}q_k − p_kq_{k+1} = (−1)^k. Dividing both sides by qk+1qkq_{k+1}q_k gives the result for xk+1−xkx_{k+1}-x_k.

Therefore, odd-indexed convergents are always greater than their adjacent convergents, while even-indexed convergents are always smaller than their adjacent convergents: the convergents alternate.

If we look only at the even-indexed (odd-indexed) convergents, the sequence is also monotonically increasing (decreasing), because

xk+2−xk=(−1)k+1qk+2qk+1+(−1)kqk+1qk=(−1)k(qk+2−qk)qk+2qk+1qk=(−1)kak+2qk+2qkx_{k+2}-x_k = \dfrac{(-1)^{k+1}}{q_{k+2}q_{k+1}}+\dfrac{(-1)^{k}}{q_{k+1}q_{k}} = \dfrac{(-1)^k(q_{k+2}-q_k)}{q_{k+2}q_{k+1}q_k} = \dfrac{(-1)^ka_{k+2}}{q_{k+2}q_k}

is positive (negative) when kk is even (odd). At the same time, because the recurrence qk=akqk−1+qk−2q_{k}=a_kq_{k-1}+q_{k-2} holds, the denominator qkq_k grows at least as fast as the Fibonacci sequence. Thus, the difference between adjacent terms must approach zero. This shows that the even-indexed and odd-indexed convergents approach the same limit from below and above, respectively. This proves that every infinite simple continued fraction converges. The way convergents approach the corresponding real number is shown below:

Figure: golden ratio convergents
Upper and lower convergents

For a real number xx and its convergent xkx_k, if xk>xx_k>x (xk<xx_k<x), then xkx_k is called an upper (lower) convergent of xx.

We have already shown that upper convergents are exactly the odd-indexed convergents, while lower convergents are exactly the even-indexed convergents.

Using the difference formula, we can write the real number xx as an alternating series:

x=a0+∑k=0∞(−1)kqk+1qk.x = a_0+\sum_{k=0}^{\infty}\dfrac{(-1)^k}{q_{k+1}q_k}.

The convergents and remainders in the definition of a continued fraction are the partial sums and remainders of this series.

The difference formula also gives a direct estimate of the error produced when a convergent approximates a real number:

Error

Let xk=pkqk≠xx_k=\dfrac{p_k}{q_k}\neq x be the convergent of the real number xx with index kk. Then

xk−x=(−1)kqk(rk+1qk+qk−1),x_k - x = \dfrac{(-1)^k}{q_k\left(r_{k+1}q_k+q_{k-1}\right)},

Here rk+1r_{k+1} is the remainder of the real number xx with index k+1k+1. Consequently,

12qk+12≤1qk(qk+qk+1)≤∣x−pkqk∣≤1qkqk+1≤1qk2.\dfrac{1}{2q_{k+1}^2} \le \dfrac{1}{q_k(q_k+q_{k+1})} \le \left|x-\frac{p_k}{q_k}\right| \le \dfrac{1}{q_kq_{k+1}} \le \dfrac{1}{q_k^2}.
Proof

Since x=[a0,a1,⋯ ,ak,rk+1]x=[a_0,a_1,\cdots,a_k,r_{k+1}], and the difference formula for convergents also holds for formal continued fractions, we have

x−xk=(−1)kqk(rk+1qk+qk−1),x-x_k = \dfrac{(-1)^k}{q_k\left(r_{k+1}q_k+q_{k-1}\right)},

where rk+1qk+qk−1r_{k+1}q_k+q_{k-1} is the denominator of the k+1k+1-th convergent of this formal continued fraction obtained from the recurrence.

To complete the following inequality estimate, we only need to note that when xk≠xx_k\neq x, we always have

1≤ak+1≤rk+1≤ak+1+1,1\le a_{k+1}\le r_{k+1} \le a_{k+1}+1,

so

qk+1=ak+1qk+qk−1≤rk+1qk+qk−1≤qk+(ak+1qk+qk−1)=qk+qk+1.q_{k+1}=a_{k+1}q_k+q_{k-1}\le r_{k+1}q_k+q_{k-1} \le q_k+(a_{k+1}q_k+q_{k-1}) = q_k+q_{k+1}.

Therefore,

1qk(qk+qk+1)≤∣x−pkqk∣=1qk(rk+1qk+qk−1)≤1qkqk+1.\dfrac{1}{q_k(q_k+q_{k+1})} \le \left|x-\frac{p_k}{q_k}\right| = \dfrac{1}{q_k\left(r_{k+1}q_k+q_{k-1}\right)} \le \dfrac{1}{q_kq_{k+1}}.

To obtain the outer bounds, also note that qk≤qk+1q_k\le q_{k+1}.

The difference formula in this section has the following simple corollary: all convergents pkqk\dfrac{p_k}{q_k} are reduced.

Corollary

For any real number xx, if the numerator and denominator of the convergent xk=pkqkx_k=\dfrac{p_k}{q_k} are given by the recurrence, then pkqk\dfrac{p_k}{q_k} is a reduced fraction, that is, gcd⁡(pk,qk)=1\gcd(p_k,q_k)=1.

Proof

Apply Bézout's identity to the difference formula.

In fact, solutions to a binary linear Diophantine equation can be found using continued fractions.

Solving a binary linear Diophantine equation

Given A,B,C∈ZA, B, C \in \mathbf Z, find x,y∈Zx, y \in \mathbf Z such that Ax+By=CAx + By = C.

Solution

Although this problem is usually solved using the extended Euclidean algorithm, it can also be solved using continued fractions.

Suppose that AB=[a0,a1,⋯ ,ak]\dfrac{A}{B}=[a_0, a_1, \cdots, a_k]. We proved above that pkqk−1−pk−1qk=(−1)k−1p_k q_{k-1} - p_{k-1} q_k = (-1)^{k-1}. Replacing pkp_k and qkq_k with AA and BB gives

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 gg divides CC, one solution is x=(−1)k−1Cgqk−1x = (-1)^{k-1}\dfrac{C}{g} q_{k-1} and y=(−1)kCgpk−1y = (-1)^{k}\dfrac{C}{g} p_{k-1}; otherwise, there is no solution.

C++

// Return (x,y) such that Ax+By=C.
// Assume that such (x,y) exists.
auto dio(int A, int B, int C) {
  std::vector<int> p, q;
  std::tie(p, q) = convergents(fraction(A, B));
  C /= A / p.back();
  int t = p.size() % 2 ? -1 : 1;
  return std::make_pair(t * C * q.end()[-2], -t * C * p.end()[-2]);
}

Python

# Return (x, y) such that Ax+By=C.
# Assume 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]

Diophantine approximation

An important application of continued-fraction theory is Diophantine approximation. Diophantine approximation means approximating real numbers with rational numbers. Of course, because rational numbers are dense, we can obtain approximations with arbitrarily small error if there are no restrictions. Therefore, we need to restrict the rational numbers that may be used, for example, to rational numbers whose denominators are below a given value. This section discusses the relationship between best approximations under such restrictions and continued fractions.

Approximating real numbers with convergents

First, the error estimate for convergents immediately gives the following result:

Theorem (Dirichlet)

For an irrational number xx, there exist infinitely many reduced fractions pq\dfrac{p}{q} such that

∣x−pq∣<1q2\left|x-\dfrac{p}{q}\right| < \dfrac{1}{q^2}

holds.

Proof

By the error estimate for convergents, for an irrational number xx, the convergent with index kk, xk=pkqkx_k=\dfrac{p_k}{q_k} satisfies

∣x−pkqk∣≤1qk2.\left|x-\dfrac{p_k}{q_k}\right|\le\frac{1}{q_k^2}.

Checking the proof of the error formula shows that equality cannot hold for any irrational number xx. Therefore, the numerators and denominators of all its convergents satisfy the requirement.

This theorem can also be viewed as a corollary of the Dirichlet approximation theorem. This is nearly the best possible result. The exponent 22 in the denominator on the right-hand side cannot be improved, but the constant can be improved. Hurwitz's theorem says that the right-hand side can be reduced to 15q2\dfrac{1}{\sqrt{5}q^2}, and this is the best possible bound.

Hurwitz's theorem

For an irrational number xx, there exist infinitely many reduced fractions pq\dfrac{p}{q} such that

∣x−pq∣<15q2\left|x-\dfrac{p}{q}\right| < \dfrac{1}{\sqrt{5}q^2}

holds, and the 5\sqrt{5} on the right-hand side cannot be replaced by a larger real number.

Proof (Borel)

Borel actually proved that among any three consecutive convergents of an irrational number xx, at least one necessarily satisfies the condition above. Since there are infinitely many convergents and all are reduced fractions, the first part of Hurwitz's theorem follows.

We argue by contradiction. Suppose that there is an irrational number xx and three of its convergents xk−1,xk,xk+1x_{k-1},x_k,x_{k+1} such that

∣x−pk−1qk−1∣≥15qk−12, ∣x−pkqk∣≥15qk2, ∣x−pk+1qk+1∣≥15qk+12\left|x-\dfrac{p_{k-1}}{q_{k-1}}\right|\ge\dfrac{1}{\sqrt{5}q_{k-1}^2},\ \left|x-\dfrac{p_{k}}{q_{k}}\right|\ge\dfrac{1}{\sqrt{5}q_{k}^2},\ \left|x-\dfrac{p_{k+1}}{q_{k+1}}\right|\ge\dfrac{1}{\sqrt{5}q_{k+1}^2}

hold. Since adjacent convergents must lie on opposite sides of xx, the difference formula gives

1qk−1qk=∣pk−1qk−1−pkqk∣=∣x−pk−1qk−1∣+∣x−pkqk∣≥15qk−12+15qk2.\dfrac{1}{q_{k-1}q_{k}}=\left|\dfrac{p_{k-1}}{q_{k-1}}-\dfrac{p_{k}}{q_{k}}\right|=\left|x-\dfrac{p_{k-1}}{q_{k-1}}\right|+\left|x-\dfrac{p_{k}}{q_{k}}\right|\ge\dfrac{1}{\sqrt{5}q_{k-1}^2}+\dfrac{1}{\sqrt{5}q_{k}^2}.

This can be written as an inequality for the quotient qkqk−1\dfrac{q_{k}}{q_{k-1}}:

qkqk−1+qk−1qk≤5.\dfrac{q_k}{q_{k-1}}+\dfrac{q_{k-1}}{q_k}\le\sqrt 5.

The left-hand side is rational and the right-hand side is irrational, so equality cannot hold. Since qk≥qk−1q_k\ge q_{k-1}, we obtain

1≤qkqk−1<5+12.1\le \dfrac{q_{k}}{q_{k-1}} < \dfrac{\sqrt{5}+1}{2}.

Similarly, we can prove

1≤qk+1qk<5+12.1\le \dfrac{q_{k+1}}{q_{k}} < \dfrac{\sqrt{5}+1}{2}.

However, by the recurrence and the two inequalities, we have

ak+1=qk+1qk−qk−1qk<5+12−5−12=1a_{k+1} = \frac{q_{k+1}}{q_k}-\frac{q_{k-1}}{q_k} < \dfrac{\sqrt{5}+1}{2}-\dfrac{\sqrt{5}-1}{2} = 1

This contradicts the definition of a simple continued fraction. Hence Borel's conclusion holds.

To show that this bound is the best possible, it suffices to find an xx such that for every C>5C>\sqrt{5}, only finitely many reduced fractions pq\dfrac{p}{q} satisfy

∣x−pq∣<1Cq2\left|x-\dfrac{p}{q}\right| < \dfrac{1}{Cq^2}

We now prove that ϕ=5+12\phi=\dfrac{\sqrt{5}+1}{2} is such an xx.3

Let ϕ′=−5+12\phi'=\dfrac{-\sqrt{5}+1}{2} be the conjugate root of ϕ\phi. Both are roots of the equation x2−x−1=0x^2-x-1=0. Thus, for every real number xx,

x2−x−1=(x−ϕ)(x−ϕ′).x^2-x-1 = (x-\phi)(x-\phi').

Substituting the reduced fraction pq\dfrac{p}{q} gives

1q2≤∣p2−pq−q2∣q2=∣pq−ϕ∣∣pq−ϕ′∣≤∣pq−ϕ∣(∣pq−ϕ∣+∣ϕ−ϕ′∣)<1Cq2(1Cq2+5).\dfrac{1}{q^2}\le\frac{|p^2-pq-q^2|}{q^2}=\left|\dfrac{p}{q}-\phi\right|\left|\dfrac{p}{q}-\phi'\right|\le\left|\dfrac{p}{q}-\phi\right|\left(\left|\dfrac{p}{q}-\phi\right|+|\phi-\phi'|\right)<\dfrac{1}{Cq^2}\left(\dfrac{1}{Cq^2}+\sqrt{5}\right).

For C>5C>\sqrt{5}, we can directly solve for q<C(C−5)q<\sqrt{C(C-\sqrt{5})}, so there cannot be infinitely many solutions satisfying the inequality above.

The proofs of these theorems show that convergents provide fairly good Diophantine approximations. However, they are not necessarily the best approximations. To discuss best approximations, we need to specify a measure of the quality of an approximation. There are usually two choices.

Best-approximation results may fail in some cases

The next two sections state several results about best approximations. These results may fail for certain uninteresting cases. For example, both definitions of best approximation require a strict inequality, but for a half-integer x=n+12x=n+\dfrac12 with n∈Zn\in\mathbf Z, its continued fraction can be written as [n,1,1][n,1,1]. In this case, the denominators of its first two convergents x0=nx_0=n and x1=n+1x_1=n+1 are both 11, and their distances from xx are equal. Thus, neither is a best approximation. In stating the results of this section, the reader should assume that such cases have been excluded. If the reader is not concerned with the last few convergents, or only cares about approximating irrational numbers, these extra complications can be ignored.

First-kind best approximations: intermediate fractions

First-kind best approximations use

∣x−pq∣\left|x-\dfrac{p}{q}\right|

to measure the quality of an approximation.

Best approximation of the first kind

For a real number xx and a rational number pq\dfrac{p}{q}, if for every p′q′≠pq\dfrac{p'}{q'}\neq \dfrac{p}{q} with 0<q′≤q0<q'\le q we have

∣x−pq∣<∣x−p′q′∣,\left|x-\dfrac{p}{q}\right|<\left|x-\dfrac{p'}{q'}\right|,

then the rational number pq\dfrac{p}{q} is called a best approximation of the first kind of the real number xx.

A first-kind best approximation need not be a convergent; it may be a more general fraction.

Intermediate fractions

Suppose that a real number xx has the convergent xk+1=[a0,a1,⋯ ,ak,ak+1]x_{k+1}=[a_0,a_1,\cdots,a_k,a_{k+1}], and let the integer tt satisfy 0≤t≤ak+10\le t\le a_{k+1}4. Then the fraction xk,t=[a0,a1,⋯ ,ak,t]x_{k,t}=[a_0,a_1,\cdots,a_{k},t] is called an intermediate fraction, semiconvergent, or secondary convergent of xx.5

As with convergents, an intermediate fraction greater (less) than xx is called an upper (lower) semiconvergent.

By the recurrence, an intermediate fraction can be written as

xk,t=tpk+pk−1tqk+qk−1.x_{k,t} = \frac{tp_{k}+p_{k-1}}{tq_{k}+q_{k-1}}.

It is necessarily a reduced fraction and lies between the convergents xk−1x_{k-1} and xk+1x_{k+1}. As tt increases, it gradually approaches xk+1x_{k+1}; taking the case where kk is even as an example,

xk−1=xk,0<xk,1<xk,2<⋯<xk,ak+1=xk+1.x_{k-1} = x_{k,0} < x_{k,1} < x_{k,2} < \cdots < x_{k,a_{k+1}} = x_{k+1}.

Because the numerators and denominators of convergents both increase, the numerator and denominator of an intermediate fraction xk,tx_{k,t} (t≠0t\neq 0) lie between those of xkx_{k} and xk+1x_{k+1}. If these fractions are ordered by denominator, the intermediate fractions are some fractions lying between adjacent convergents.

All first-kind best approximations are intermediate fractions, but not every intermediate fraction is a first-kind best approximation.

Theorem

Every first-kind best approximation is an intermediate fraction.

Proof

Since a0≤x≤a0+1a_0\le x\le a_0+1, a first-kind best approximation must lie between x1,0=a0x_{1,0}=a_0 and x0,1=a0+1x_{0,1}=a_0+1. All intermediate fractions can be ordered from small to large as

x1,0<x1,1<⋯<x1,a2=x3,0<…<x<…<x2,0=x0,a1<⋯<x0,1.x_{1,0}<x_{1,1}< \cdots < x_{1,a_2}=x_{3,0}<\ldots<x<\ldots<x_{2,0}=x_{0,a_1}<\cdots<x_{0,1}.

Intermediate fractions of the same order occur consecutively, and there are no gaps between intermediate fractions of different orders. This means that any rational number lying between x1,0=a0x_{1,0}=a_0 and x0,1=a0+1x_{0,1}=a_0+1, namely pq\dfrac{p}{q} must lie between two intermediate fractions xk,tx_{k,t} and xk,t+1x_{k,t+1} of the same order. Suppose without loss of generality that it is not an intermediate fraction and is smaller than xx, so

xk,t<pq<xk,t+1<x.x_{k,t}<\dfrac{p}{q}<x_{k,t+1}<x.

On the one hand,

∣xk,t−pq∣≤∣xk,t−xk,t+1∣=1((t+1)qk+qk−1)(tqk+qk−1).\left|x_{k,t}-\dfrac{p}{q}\right| \le \left|x_{k,t}-x_{k,t+1}\right| = \dfrac{1}{((t+1)q_k+q_{k-1})(tq_k+q_{k-1})}.

On the other hand,

∣xk,t−pq∣=∣q(tpk+pk−1)−p((t+1)qk+qk−1)∣q(tqk+qk−1)≥1q(tqk+qk−1).\left|x_{k,t}-\dfrac{p}{q}\right| = \dfrac{|q(tp_k+p_{k-1})-p((t+1)q_k+q_{k-1})|}{q(tq_k+q_{k-1})}\ge\dfrac{1}{q(tq_k+q_{k-1})}.

Therefore,

q>(t+1)qk+qk−1.q>(t+1)q_k+q_{k-1}.

In other words, the denominator of the rational number pq\dfrac{p}{q} is larger than the denominator of xk,t+1x_{k,t+1}, but it is not a better approximation:

∣x−pq∣>∣x−xk,t+1∣\left|x-\dfrac{p}{q}\right|>\left|x-x_{k,t+1}\right|

Therefore, it cannot be a first-kind best approximation. This shows that a fraction that is not an intermediate fraction cannot be a first-kind best approximation; equivalently, every first-kind best approximation is an intermediate fraction.

Conversely, we cannot assert that every intermediate fraction is a first-kind best approximation. However, we can give the condition under which an intermediate fraction is a first-kind best approximation.

Theorem

Every convergent is a first-kind best approximation. In addition, let 0<t<ak+10<t<a_{k+1}. Then the intermediate fraction xk,tx_{k,t} is a first-kind best approximation if and only if t>ak+12t>\dfrac{a_{k+1}}{2}, or t=ak+12t=\dfrac{a_{k+1}}{2} and rk+2>qkqk−1r_{k+2}>\dfrac{q_k}{q_{k-1}}.

Proof

We will show below that every convergent is a second-kind best approximation, and hence is necessarily a first-kind best approximation. The key issue is the intermediate fractions that are not convergents.

As stated earlier, the denominator of an intermediate fraction xk,tx_{k,t} lies between those of xkx_k and xk+1x_{k+1} and increases as tt increases, while xk,tx_{k,t} gradually approaches xk+1x_{k+1} and hence gets closer to xx. For example, when xk,t<xx_{k,t}<x, its relative positions with the neighboring intermediate fractions satisfy

xk−1<xk,t<xk+1<x<xk.x_{k-1} < x_{k,t} < x_{k+1} < x < x_{k}.

Since the denominator of xkx_k is smaller than that of xk,tx_{k,t}, the necessary condition for xk,tx_{k,t} to be a first-kind best approximation is that it, relative to xkx_k, give a closer approximation to xx. This is also sufficient: as a convergent, no fraction with a denominator smaller than that of xkx_k is a closer approximation. An intermediate fraction with a denominator larger than that of xkx_k is necessarily of the same order as xk,tx_{k,t} and, having a smaller denominator, is necessarily farther from xx. Direct calculation gives the errors of the convergent and intermediate fraction:

∣xk−x∣=1qk(rk+1qk+qk−1),∣xk,t−x∣=∣tpk+pk−1tqk+qk−1−rk+1pk+pk−1rk+1qk+qk−1∣=rk+1−t(tqk+qk−1)(rk+1qk+qk−1).\begin{aligned} \left|x_k-x\right| &= \dfrac{1}{q_k(r_{k+1}q_k+q_{k-1})},\\ \left|x_{k,t}-x\right| &= \left|\dfrac{tp_{k}+p_{k-1}}{tq_{k}+q_{k-1}}-\dfrac{r_{k+1}p_{k}+p_{k-1}}{r_{k+1}q_{k}+q_{k-1}}\right| \\ &=\dfrac{r_{k+1}-t}{(tq_{k}+q_{k-1})(r_{k+1}q_{k}+q_{k-1})}. \end{aligned}

Here we used rk+1≥ak+1>tr_{k+1}\ge a_{k+1}>t. Thus, xk,tx_{k,t} is closer than xkx_k to xx and is a first-kind best approximation if and only if

rk+1−ttqk+qk−1<1qk  ⟺  rk+1<2t+qk−1qk.\dfrac{r_{k+1}-t}{tq_{k}+q_{k-1}}<\dfrac{1}{q_k} \iff r_{k+1}<2t+\dfrac{q_{k-1}}{q_k}.

There are three possible cases:

  1. If t<at+12t<\dfrac{a_{t+1}}{2}, then 2t<at+12t<a_{t+1}. Since both sides are integers, 2t≤ak+1−12t\le a_{k+1}-1, so 2t+qk−1qk≤2t+1≤ak+1≤rt+12t+\dfrac{q_{k-1}}{q_k}\le 2t+1\le a_{k+1}\le r_{t+1}. In this case, xk,tx_{k,t} is not a first-kind best approximation;
  2. If t>at+12t>\dfrac{a_{t+1}}{2}, then 2t>at+12t>a_{t+1}. Since both sides are integers, 2t≥at+1+1>rt+12t\ge a_{t+1}+1>r_{t+1}. In this case, xk,tx_{k,t} is a first-kind best approximation;
  3. If at+1a_{t+1} is even, there is a third case, namely t=at+12t=\dfrac{a_{t+1}}{2}. The condition above is equivalent to 1rk+1=rk+1−ak+1<qk−1qk\dfrac{1}{r_{k+1}}=r_{k+1}-a_{k+1}<\dfrac{q_{k-1}}{q_k}, or rk+2>qkqk−1r_{k+2}>\dfrac{q_k}{q_{k-1}}.

Therefore, if all first-kind best approximations of a real number xx are ordered by increasing denominator, they split into several segments according to their relation to xx. Each segment consists of several (possibly zero) consecutive intermediate fractions of the same order and always ends with a convergent. Within a segment they remain on the same side of xx, while successive segments alternate between the two sides of xx.

Example: first-kind best approximations of π\pi

Since π=[3,7,15,1,292,⋯ ]\pi=[3,7,15,1,292,\cdots], its first 15 first-kind best approximations in order of increasing denominator are:

x0=31, x0,4=134, x0,5=165, x0,6=196, x1=227,x1,8=17957, x1,9=20164, x1,10=22371, x1,11=24578, x1,12=26785,x1,13=28992,x1,14=31199, x2=333106, x3=355113, x3,146=5216316604.\begin{aligned} &x_0 = \dfrac{3}{1},\ x_{0,4} = \dfrac{13}{4},\ x_{0,5} = \dfrac{16}{5},\ x_{0,6} = \dfrac{19}{6},\ x_1 = \dfrac{22}{7},\\ &x_{1,8} = \dfrac{179}{57},\ x_{1,9} = \dfrac{201}{64},\ x_{1,10} = \dfrac{223}{71},\ x_{1,11} = \dfrac{245}{78},\ x_{1,12} = \dfrac{267}{85},\\ &x_{1,13} = \dfrac{289}{92}, x_{1,14} = \dfrac{311}{99},\ x_2 = \dfrac{333}{106},\ x_3 = \dfrac{355}{113},\ x_{3,146} = \dfrac{52163}{16604}. \end{aligned}

Second-kind best approximations

Second-kind best approximations use ∣qx−p∣|qx-p| to measure the quality of an approximation.

Best approximation of the second kind

For a real number xx and a rational number pq\dfrac{p}{q}, if for every p′q′≠pq\dfrac{p'}{q'}\neq \dfrac{p}{q} with 0<q′≤q0<q'\le q we have

∣qx−p∣<∣q′x−p′∣,\left|qx-p\right|<\left|q'x-p'\right|,

then the rational number pq\dfrac{p}{q} is called a best approximation of the second kind of the real number xx.

The condition for a second-kind best approximation is equivalent to

∣x−pq∣<q′q∣x−p′q′∣.\left|x-\dfrac{p}{q}\right|<\dfrac{q'}{q}\left|x-\dfrac{p'}{q'}\right|.

Because q′≤qq'\le q, the condition for a second-kind best approximation is stricter than that for a first-kind best approximation.

A second-kind best approximation can be, and only can be, a convergent.

Theorem

Every second-kind best approximation is a convergent, and every convergent is also a second-kind best approximation.

Proof

To prove the first part, since every second-kind best approximation is also a first-kind best approximation, it suffices to show that an intermediate fraction that is not a convergent cannot be a second-kind best approximation. Let xk,t=pqx_{k,t}=\dfrac{p}{q} be an intermediate fraction but not a convergent. Suppose that xk,t<xx_{k,t}<x; then

xk−1<xk,t<xk+1<x<xk.x_{k-1} < x_{k,t} < x_{k+1} < x < x_{k}.

The error between xk,tx_{k,t} and xx satisfies

∣xk,t−x∣≥∣xk,t−xk+1∣=∣pq−pk+1qk+1∣=∣pqk+1−pk+1q∣qqk+1≥1qqk+1,|x_{k,t}-x|\ge |x_{k,t}-x_{k+1}|=\left|\dfrac{p}{q}-\dfrac{p_{k+1}}{q_{k+1}}\right|=\dfrac{|pq_{k+1}-p_{k+1}q|}{qq_{k+1}}\ge\dfrac{1}{qq_{k+1}},

and using the error estimate for convergents, we always have

∣qxk,t−p∣≥1qk+1≥∣qkxk−pk∣,|qx_{k,t}-p| \ge \dfrac{1}{q_{k+1}} \ge |q_kx_k-p_k|,

so the approximation by xk,tx_{k,t} is no better than the approximation by xkx_k, whose denominator is smaller. Hence it cannot be a second-kind best approximation.

Conversely, to prove the second part, every convergent xk=pkqkx_k=\dfrac{p_k}{q_k} is a second-kind best approximation. We need to show that for every fraction pq\dfrac{p}{q} with q≤qkq\le q_k, ∣qkx−pk∣<∣qx−p∣|q_kx-p_k|<|qx-p|. Ignoring the half-integer case, we may assume k>0k>0. First, the error estimate for convergents gives

∣qk−1x−pk−1∣≥1qk−1+qk≥1qk+1≥∣qkx−pk∣.|q_{k-1} x-p_{k-1}| \ge \frac{1}{q_{k-1}+q_{k}} \ge \dfrac{1}{q_{k+1}}\ge |q_kx-p_k|.

Equality holds throughout if and only if ak+1=1a_{k+1}=1 and it is the final term of the continued fraction. Excluding this case, xk−1=pk−1qk−1x_{k-1}=\dfrac{p_{k-1}}{q_{k-1}} is strictly worse than xk=pkqkx_k=\dfrac{p_k}{q_k}.

Take any fraction pq≠xk\dfrac{p}{q}\neq x_k with 0<q≤qk0<q\le q_k. Since the difference formula gives pkqk−1−pk−1qk=(−1)k−1p_{k}q_{k-1} − p_{k-1}q_{k} = (−1)^{k-1}, Cramer's rule shows that the linear system

{λpk+μpk−1=p,λqk+μqk−1=q\begin{cases} \lambda p_k+\mu p_{k-1} = p,\\ \lambda q_k+\mu q_{k-1} = q \end{cases}

necessarily has a unique integer solution (λ,μ)(\lambda,\mu). If λμ>0\lambda\mu>0, then q>∣λ∣qk≥qkq>|\lambda|q_k\ge q_k, a contradiction. Otherwise, λμ≤0\lambda\mu\le 0, so λ\lambda and μ\mu have opposite signs. Since qk−1x−pk−1q_{k-1}x-p_{k-1} and qkx−pkq_kx-p_k also have opposite signs, λ(qk−1x−pk−1)\lambda(q_{k-1}x-p_{k-1}) and μ(qkx−pk)\mu(q_kx-p_k) have the same sign, and therefore

∣qx−p∣=∣λ∣∣qkx−pk∣+∣μ∣∣qk−1x−pk−1∣>∣qkx−pk∣.|qx-p|=|\lambda||q_kx-p_k|+|\mu||q_{k-1}x-p_{k-1}|>|q_{k}x-p_{k}|.

The final inequality is strict because xk−1x_{k-1} is strictly worse than xkx_k and pq≠xk\dfrac{p}{q}\neq x_k. This proves that xkx_k is a second-kind best approximation.

This property shows that convergents really are quite good Diophantine approximations.

Identifying convergents

Second-kind best approximations provide a necessary and sufficient condition for determining whether a fraction is a convergent. This means that we can determine whether a fraction is a convergent by checking its relative approximation quality. Legendre's criterion provides a way to identify convergents from the absolute quality of the approximation. The original statement of Legendre's criterion gives a necessary and sufficient condition, but its form is not practical. This section gives a simplified version of Legendre's criterion and explains that it omits few convergents.

Theorem (Legendre)

For a real number xx and a fraction pq\dfrac{p}{q}, if

∣x−pq∣<12q2\left|x−\dfrac{p}{q}\right|<\dfrac{1}{2q^2}

then pq\dfrac{p}{q} is necessarily a convergent of xx.

Proof

Let ϵ∈{−1,1}\epsilon\in\{-1,1\} and θ∈(0,1/2)\theta\in(0,1/2) be constants satisfying

x−pq=ϵθq2x−\dfrac{p}{q} = \dfrac{\epsilon\theta}{q^2}

Expand the rational number pq\dfrac{p}{q} as a continued fraction [a0,a1,⋯ ,an][a_0,a_1,\cdots,a_n]. A rational number has two continued-fraction representations whose nn values differ by exactly one, so we can choose the representation for which (−1)n=ϵ(-1)^n=\epsilon, and let the convergent of this representation be pkqk\dfrac{p_k}{q_k}. Let the real number ω\omega satisfy

x=ωpn+pn−1ωqn+qn−1.x = \dfrac{\omega p_n+p_{n-1}}{\omega q_n+q_{n-1}}.

Then necessarily

ϵθq2=x−pq=x−pnqn=pn−1qn−pnqn−1(ωqn+qn−1)qn=(−1)n(ωqn+qn−1)qn.\dfrac{\epsilon\theta}{q^2} = x−\dfrac{p}{q} = x-\dfrac{p_n}{q_n} = \dfrac{p_{n-1}q_n-p_nq_{n-1}}{(\omega q_n+q_{n-1})q_n} = \dfrac{(-1)^n}{(\omega q_n+q_{n-1})q_n}.

Hence,

θ=qnωqn+qn−1.\theta = \dfrac{q_n}{\omega q_n+q_{n-1}}.

This shows that

ω=1θ−qn−1qn>1.\omega=\dfrac{1}{\theta}-\dfrac{q_{n-1}}{q_n}>1.

Expand ω\omega as a continued fraction [b0,b1,⋯ ][b_0,b_1,\cdots]. Then

x=ωpn+pn−1ωqn+qn−1=[a0,a1,⋯ ,an,ω]=[a0,a1,⋯ ,an,b0,b1,⋯ ].x = \dfrac{\omega p_n+p_{n-1}}{\omega q_n+q_{n-1}} = [a_0,a_1,\cdots,a_n,\omega] = [a_0,a_1,\cdots,a_n,b_0,b_1,\cdots].

This is a valid simple continued fraction, so pq\dfrac{p}{q} is a convergent of xx.

In fact, this proof shows that the necessary and sufficient condition for pq\dfrac{p}{q} to be a convergent is ω>1\omega>1 in the proof above, which is precisely the original form of Legendre's criterion.

This criterion shows that any approximation that is sufficiently good must be a convergent. The next theorem shows that there are enough convergents of this quality: at least half of the convergents satisfy the condition.

Theorem (Valhen)

Among any two consecutive convergents of a real number xx, at least one satisfies

∣x−pq∣<12q2.\left|x−\dfrac{p}{q}\right|<\dfrac{1}{2q^2}.
Proof

Suppose otherwise. There is a real number xx with two consecutive convergents xk−1x_{k-1} and xkx_k satisfying

∣x−pkqk∣≥12qk2, ∣x−pk+1qk+1∣≥12qk+12.\left|x-\dfrac{p_k}{q_k}\right|\ge \dfrac{1}{2q_{k}^2},\ \left|x-\dfrac{p_{k+1}}{q_{k+1}}\right|\ge \dfrac{1}{2q_{k+1}^2}.

Since xx lies between xk−1x_{k-1} and xkx_k,

12qk2+12qk+12≤∣x−pkqk∣+∣x−pk+1qk+1∣=∣pkqk−pk+1qk+1∣=1qkqk+1.\dfrac{1}{2q_{k}^2} + \dfrac{1}{2q_{k+1}^2} \le \left|x-\dfrac{p_k}{q_k}\right| + \left|x-\dfrac{p_{k+1}}{q_{k+1}}\right| = \left|\dfrac{p_k}{q_k}-\dfrac{p_{k+1}}{q_{k+1}}\right| = \dfrac{1}{q_kq_{k+1}}.

This implies qk=qk+1q_k=q_{k+1}. Therefore, necessarily k=0k=0 and a1=1a_1=1. The first two convergents are then x0=a0x_0=a_0 and x1=a0+1x_1=a_0+1. Thus the only counterexample to the statement is a half-integer, which, as explained earlier, is not considered in this article.

Geometric Interpretation

The theory of continued fractions has an elegant geometric interpretation.

Figure: continued convergents geometry

As shown in the figure, for a real number ξ>0\xi>0, the line y=ξxy=\xi x divides the lattice points in the first quadrant (including points on the xx- and yy-axes but excluding the origin; this convention applies below) into two parts, above and below. When ξ\xi is rational, points on the line y=ξxy=\xi x are counted both as points above the line and as points below it. Consider the convex hulls of these two sets of points. Then the odd-indexed convergents are the vertices of the convex hull of the upper part, and the even-indexed convergents are the vertices of the convex hull of the lower part. The lattice points on the line segment between two adjacent vertices of a convex hull are the intermediate fractions. The figure shows the convergents and intermediate fractions (gray points) for ξ=97\xi=\dfrac{9}{7}.

Most of the conclusions about continued fractions above have corresponding geometric interpretations:

Geometric Interpretation
  • Each fraction ν=pq\nu=\dfrac{p}{q} corresponds to a lattice point ν⃗=(q,p)\vec\nu=(q,p) in the first quadrant; the magnitude of the fraction corresponds to the slope of the line joining the point to the origin.

  • The direction vector of the line y=ξxy=\xi x is ξ⃗=(1,ξ)\vec\xi=(1,\xi). Using the concept of the cross product (x1,y1)×(x2,y2)=x1y2−x2y1(x_1,y_1)\times(x_2,y_2)=x_1y_2-x_2y_1, the sign of ξ⃗×ν⃗=p−qξ\vec\xi\times\vec\nu=p-q\xi determines whether a point lies above or below the line. Thus, points above the line correspond to fractions greater than or equal to ξ\xi, while points below the line correspond to fractions less than or equal to ξ\xi. The absolute value of the cross product, ∣ξ⃗×ν⃗∣|\vec\xi\times\vec\nu|, is proportional to the distance from ν⃗\vec\nu to the line y=ξxy=\xi x:

    ∣p−qx∣1+ξ2,\dfrac{|p-qx|}{\sqrt{1+\xi^2}},

    which corresponds to how closely the fraction ν\nu approximates the real number ξ\xi.

  • If the point corresponding to the convergent ξk=pkqk\xi_k=\dfrac{p_k}{q_k} is denoted by ξ⃗k=(pk,qk)\vec\xi_k=(p_k,q_k), then the recurrence can be written as

    ξ⃗k=akξ⃗k−1+ξ⃗k−2.\vec\xi_k = a_k\vec\xi_{k-1} + \vec\xi_{k-2}.

    The starting points of the recurrence are ξ−2=(1,0)\xi_{-2} = (1,0) and ξ−1=(0,1)\xi_{-1} = (0,1).

  • For an integer tt, if 0≤t≤ak0\le t\le a_k, then the point

    ξ⃗k−1,t=tξ⃗k−1+ξ⃗k−2\vec\xi_{k-1,t} = t\vec\xi_{k-1} + \vec\xi_{k-2}

    lies on the segment joining ξ⃗k−2\vec\xi_{k-2} and ξ⃗k\vec\xi_k. These points correspond to the intermediate fractions ξk−1,t\xi_{k-1,t}.

  • All convergents and intermediate fractions can be constructed geometrically. Start with the points ξ⃗−2=(1,0)\vec\xi_{-2}=(1,0) and ξ⃗−1=(0,1)\vec\xi_{-1}=(0,1). The two points lie on opposite sides of the line y=ξxy=\xi x, which means that ξ⃗×ξ⃗−2\vec\xi\times\vec\xi_{-2} and ξ⃗×ξ⃗−1\vec\xi\times\vec\xi_{-1} have opposite signs. Add ξ⃗−1\vec\xi_{-1} to ξ⃗−2\vec\xi_{-2} by vector addition until it is no longer possible to continue without crossing the line y=ξxy=\xi x; call the result ξ⃗0\vec\xi_0. It is still on the opposite side from ξ⃗−1\vec\xi_{-1}. Then add ξ⃗0\vec\xi_0 to ξ⃗−1\vec\xi_{-1} until it is no longer possible to continue without crossing the line y=ξxy=\xi x; call the result ξ⃗1\vec\xi_1. It is still on the opposite side from ξ⃗0\vec\xi_0. This process can continue indefinitely, unless some ξ⃗n\vec\xi_n lands exactly on the line y=ξxy=\xi x after finitely many steps. The latter means that ξ⃗\vec\xi and ξ⃗n\vec\xi_n are collinear, that is, ξ=pnqn\xi=\dfrac{p_n}{q_n} is rational. This process produces the figure shown above. Boris Delaunay vividly called it the nose-streching algorithm6.

  • To quickly calculate how many times ξ⃗k−1\vec\xi_{k-1} needs to be added to ξ⃗k−2\vec\xi_{k-2} at each step, we can use the cross product. Since ξ⃗×ξ⃗k−1\vec\xi\times\vec\xi_{k-1} and ξ⃗×ξ⃗k−2\vec\xi\times\vec\xi_{k-2} have opposite signs, let ξ⃗k−1,t=tξ⃗k−1+ξ⃗k−2\vec\xi_{k-1,t}=t\vec\xi_{k-1}+\vec\xi_{k-2} denote the result of adding ξ⃗k−1\vec\xi_{k-1} to ξ⃗k−2\vec\xi_{k-2} tt times. Then ξ⃗×ξ⃗k−1,t=t(ξ⃗×ξ⃗k−1)+(ξ⃗×ξ⃗k−2)\vec\xi\times\vec\xi_{k-1,t}=t(\vec\xi\times\vec\xi_{k-1})+(\vec\xi\times\vec\xi_{k-2}) does not change sign exactly when the line has not been crossed. Before the sign changes, the absolute value of ξ⃗×ξ⃗k−1,t\vec\xi\times\vec\xi_{k-1,t} gradually decreases. Define

    rk=∣ξ⃗×ξ⃗k−2ξ⃗×ξ⃗k−1∣=−ξ⃗×ξ⃗k−2ξ⃗×ξ⃗k−1.r_{k} = \left|\dfrac{\vec\xi\times\vec\xi_{k-2}}{\vec\xi\times\vec\xi_{k-1}}\right| = -\dfrac{\vec\xi\times\vec\xi_{k-2}}{\vec\xi\times\vec\xi_{k-1}}.

    Then the maximum number of decreases is

    ak=⌊rk⌋=⌊∣qk−1ξ−pk−1qk−2ξ−pk−2∣⌋.a_{k} = \lfloor r_{k}\rfloor = \left\lfloor\left|\dfrac{q_{k-1}\xi-p_{k-1}}{q_{k-2}\xi-p_{k-2}}\right|\right\rfloor.

    This is the kk-th term of the continued-fraction expansion. Moreover, rkr_k is the remainder of the continued-fraction expansion and satisfies

    rk=−qk−1ξ−pk−1qk−2ξ−pk−2  ⟺  ξ=pk−1rk+pk−2qk−1rk+qk−2.r_k = -\dfrac{q_{k-1}\xi-p_{k-1}}{q_{k-2}\xi-p_{k-2}} \iff \xi = \dfrac{p_{k-1}r_k + p_{k-2}}{q_{k-1}r_k+q_{k-2}}.

    This is the continued-fraction relation ξ=[a0,a1,⋯ ,ak−1,rk]\xi = [a_0,a_1,\cdots,a_{k-1},r_k].

  • Since each vector addition changes ξ⃗×ξ⃗k−1,t\vec\xi\times\vec\xi_{k-1,t} by a step of size ∣ξ⃗×ξ⃗k−1∣|\vec\xi\times\vec\xi_{k-1}|, the final remaining distance ∣ξ⃗×ξ⃗k∣|\vec\xi\times\vec\xi_k| must be strictly smaller than ∣ξ⃗×ξ⃗k−1∣|\vec\xi\times\vec\xi_{k-1}|. This shows that the approximation quality of the convergents, measured by ∣qx−p∣|qx-p|, strictly improves as kk increases.

  • Using the rules of the cross product,

    ξ⃗k×ξ⃗k+1=ξ⃗k×(ak+1ξ⃗k+ξ⃗k−1)=ξ⃗k×ξ⃗k−1=−ξ⃗k−1×ξ⃗k.\vec\xi_{k}\times\vec\xi_{k+1} = \vec\xi_{k}\times(a_{k+1}\vec\xi_k+\vec\xi_{k-1}) = \vec\xi_{k}\times\vec\xi_{k-1} = -\vec\xi_{k-1}\times\vec\xi_{k}.

    By induction,

    ξ⃗k×ξ⃗k+1=(−1)k+2ξ⃗k−2×ξ⃗k−1=(−1)k.\vec\xi_{k}\times\vec\xi_{k+1} = (-1)^{k+2}\vec\xi_{k-2}\times\vec\xi_{k-1} = (-1)^{k}.

    This is the difference formula for convergents, pk+1qk−pkqk+1=(−1)kp_{k+1}q_k-p_kq_{k+1}=(-1)^k.

  • The area between the upper and lower convex hulls can be partitioned into several (possibly infinitely many) triangles, each with vertices ξ⃗k−2\vec\xi_{k-2}, ξ⃗k\vec\xi_k, and 0⃗\vec 0. The area of such a triangle is

    12∣ξ⃗k−2×ξ⃗k∣=12∣ξ⃗k−2×(akξ⃗k−1+ξ⃗k−2)∣=ak2∣ξ⃗k−2×ξ⃗k−1∣=ak2.\dfrac12|\vec\xi_{k-2}\times\vec\xi_k| = \dfrac12|\vec\xi_{k-2}\times(a_k\vec\xi_{k-1}+\vec\xi_{k-2})| = \dfrac{a_k}{2}|\vec\xi_{k-2}\times\vec\xi_{k-1}| = \dfrac{a_k}{2}.

    By Pick's theorem, if II and BB are respectively the numbers of lattice points in the interior and on the boundary of the triangle, then

    I+B2−1=ak2.I + \dfrac{B}{2} - 1 = \dfrac{a_k}{2}.

    It is also known that the triangle boundary already contains the ak+2a_k+2 lattice points {0⃗}∪{ξ⃗k−1,t:0≤t≤ak}\{\vec 0\}\cup\{\vec\xi_{k-1,t}:0\le t\le a_k\}. Therefore, it must have I=0I=0 and B=ak+2B=a_k+2. Thus, there are no more lattice points on the edges of the triangle and none in its interior. In other words, qkq_k and pkp_k are coprime, the intermediate fractions are all the lattice points on the edge joining ξ⃗k−2\vec\xi_{k-2} and ξ⃗k\vec\xi_k, and every lattice point in the first quadrant lies inside one of the two convex hulls.

The upper and lower convex hulls obtained in this way are called the Klein polygon. Similar definitions can be made in higher-dimensional spaces, yielding the Klein polyhedron, which generalizes the concept of continued fractions to higher-dimensional spaces.

The Continued-Fraction Tree

Main article: Stern–Brocot tree and Farey sequence

The Stern–Brocot tree is a binary search tree storing all fractions in [0,∞][0,\infty]. A finite continued fraction actually encodes the path from the root to the position of a fraction in the Stern–Brocot tree. In other words, the continued-fraction representation [a0,a1,⋯ ,an−1,1][a_0,a_1,\cdots,a_{n-1},1] of a rational number xx means that, starting from the tree root 11\dfrac{1}{1}, we first move to the right child a0a_0 times, then to the left child a1a_1 times, alternating directions, until moving an−1a_{n-1} times in one direction. Note that only the continued-fraction representation ending in 11 may be used here.

Interpreting a continued-fraction representation as a path in the Stern–Brocot tree gives an algorithm for comparing continued fractions.

Comparing Continued-Fraction Values

Given continued fractions α=[α0,α1,⋯ ,αn]\alpha=[\alpha_0,\alpha_1,\cdots,\alpha_n] and β=[β0,β1,⋯ ,βm]\beta=[\beta_0,\beta_1,\cdots,\beta_m], compare their values.

Solution

First convert both continued-fraction representations to forms ending in 11. Without loss of generality, assume that the representations given in the problem already have this form, so αn=βm=1\alpha_n=\beta_m=1. Since even positions (with indices starting from 00) give the number of moves to the right and odd positions give the number of moves to the left, α<β\alpha<\beta if and only if, in lexicographic order,

(α0,−α1,α2,⋯ ,(−1)n−1αn−1,0,⋯ )<(β0,−β1,β2,⋯ ,(−1)m−1βm−1,0,⋯ ).(\alpha_0,-\alpha_1,\alpha_2,\cdots,(-1)^{n-1}\alpha_{n-1},0,\cdots)<(\beta_0,-\beta_1,\beta_2,\cdots,(-1)^{m-1}\beta_{m-1},0,\cdots).

Compared with the continued-fraction representations, alternately add positive and negative signs, remove the final 11, and pad shorter positions with 00.

C++

// Expand [..., n] to [..., n-1, 1] if needed.
void expand(std::vector<int>& a) {
  if (a.size() == 1 || a.back() > 1) {
    --a.back();
    a.push_back(1);
  }
}

// Check if a is smaller than b.
bool less_than(std::vector<int> a, std::vector<int> b) {
  expand(a);
  expand(b);
  for (int i = 0; i < a.size() - 1 || i < b.size() - 1; ++i) {
    int d = (i < a.size() - 1 ? a[i] : 0) - (i < b.size() - 1 ? b[i] : 0);
    if (i & 1) d = -d;
    if (d < 0) {
      return true;
    } else if (d > 0) {
      return false;
    }
  }
  return false;
}

Python

# Expand [..., n] to [..., n-1, 1] if needed.
def expand(a):
    if a[-1] != 1 or len(a) == 1:
        a[-1] -= 1
        a.append(1)
    return a


# Check if a is smaller than b.
def less_than(a, b):
    a = expand(a)
    b = expand(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
Best Interior Point

Given 01≤p0q0<p1q1≤10\dfrac{0}{1}\le\dfrac{p_0}{q_0}<\dfrac{p_1}{q_1}\le\dfrac{1}{0}, find the rational number pq\dfrac{p}{q} such that p0q0<pq<p1q1\dfrac{p_0}{q_0}<\dfrac{p}{q}<\dfrac{p_1}{q_1} and (q,p)(q,p) is minimal.

Solution

Since the Stern–Brocot tree is both a binary search tree for fractions in [0,∞][0,\infty] and a Cartesian tree of pairs (q,p)(q,p), the problem can almost be transformed into finding the LCA (lowest common ancestor) of two nodes in the Stern–Brocot tree. However, an LCA only handles the closed-interval case, where the LCA may itself be an endpoint. To avoid additional case analysis, we can first construct p0q0+ε\dfrac{p_0}{q_0}+\varepsilon and p1q1−ε\dfrac{p_1}{q_1}-\varepsilon, and then compute their LCA. Once the paths from the root to the nodes have been computed using continued fractions, the LCA is simply their longest common path.

To construct x±εx\pm\varepsilon, first move right (left) once at node xx, and then move left (right) ∞\infty times. In the language of continued fractions, for a fraction x=[a0,a1,⋯ ,an−1,1]x=[a_0,a_1,\cdots,a_{n-1},1], we know that x±εx\pm\varepsilon must be [a0,a1,⋯ ,an−1+1,∞][a_0,a_1,\cdots,a_{n-1}+1,\infty] and [a0,a1,⋯ ,an−1,1,∞][a_0,a_1,\cdots,a_{n-1},1,\infty], respectively. Thus, we only need to compare these two continued fractions and define the larger (smaller) one as x±εx\pm\varepsilon.

C++

// Get X +- EPSILON.
auto pm_eps(std::vector<int> a) {
  constexpr int inf = 0x3f3f3f3f;
  // Deal with empty continued fraction for 1/0.
  if (a.empty()) {
    a.emplace_back(inf);
  }
  auto b = a;
  expand(b);
  a.emplace_back(inf);
  b.emplace_back(inf);
  return less_than(a, b) ? std::make_pair(a, b) : std::make_pair(b, a);
}

// Find the lexicographically smallest (q, p)
//   such that p0/q0 < p/q < p1/q1.
auto middle(int p0, int q0, int p1, int q1) {
  auto a0 = pm_eps(fraction(p0, q0)).second;
  auto a1 = pm_eps(fraction(p1, q1)).first;
  std::vector<int> a;
  for (int i = 0; i < a0.size() || i < a1.size(); ++i) {
    if (a0[i] == a1[i]) {
      a.emplace_back(a0[i]);
    } else {
      a.emplace_back(std::min(a0[i], a1[i]) + 1);
      break;
    }
  }
  auto pq = convergents(a);
  return std::make_pair(pq.first.back(), pq.second.back());
}

Python

# Get X +- EPSILON.
def pm_eps(a):
    # Deal with empty continued fraction for 1/0.
    if not a:
        a.append(float("inf"))
    b = expand(a.copy())
    a.append(float("inf"))
    b.append(float("inf"))
    return (a, b) if less_than(a, b) else (b, a)


# Find the 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))):
        if a0[i] == a1[i]:
            a.append(a0[i])
        else:
            a.append(int(min(a0[i], a1[i])) + 1)
            break
    p, q = convergents(a)
    return p[-1], q[-1]
GCJ 2019, Round 2 - New Elements: Part 2

Given NN pairs of positive integers (Ci,Ji)(C_i,J_i), find a pair of positive integers (x,y)(x,y) such that {Cix+Jiy}\{C_ix+J_iy\} is strictly increasing. Among all pairs satisfying the requirement, output the lexicographically smallest one.

Solution

Let Ai=Ci−Ci−1A_i=C_i-C_{i-1} and Bi=Ji−Ji−1B_i=J_i-J_{i-1} without loss of generality. The problem becomes finding (x,y)(x,y) such that all Aix+BiyA_ix+B_iy are integers. These pairs can be divided into four cases:

  1. The case Ai,Bi>0A_i,B_i>0 can be ignored because we have already assumed (x,y)>0(x,y)>0;
  2. The case Ai,Bi≤0A_i,B_i\le 0 directly gives IMPOSSIBLE;
  3. The case Ai>0,Bi≤0A_i>0,B_i\le 0 is equivalent to the constraint yx<Ai−Bi\dfrac{y}{x}<\dfrac{A_i}{-B_i};
  4. The case Ai≤0,Bi>0A_i\le 0,B_i>0 is equivalent to the constraint yx>−AiBi\dfrac{y}{x}>\dfrac{-A_i}{B_i}.

Therefore, let p0q0\dfrac{p_0}{q_0} be the largest −AiBi\dfrac{-A_i}{B_i} among the fourth case, and let p1q1\dfrac{p_1}{q_1} be the smallest Ai−Bi\dfrac{A_i}{-B_i} among the third case. The original problem becomes finding the lexicographically smallest (q,p)(q,p) such that p0q0<pq<p1q1\dfrac{p_0}{q_0}<\dfrac{p}{q}<\dfrac{p_1}{q_1}.

C++

void solve() {
  int n;
  std::cin >> n;
  std::vector<int> C(n), J(n);
  // p0/q0 < y/x < p1/q1
  int p0 = 0, q0 = 1, p1 = 1, q1 = 0;
  bool fail = false;
  for (int i = 0; i < n; ++i) {
    std::cin >> C[i] >> J[i];
    if (i) {
      int A = C[i] - C[i - 1];
      int B = J[i] - J[i - 1];
      if (A <= 0 && B <= 0) {
        fail = true;
        break;
      } else if (B > 0 && A < 0) {  // y/x > (-A)/B if B > 0
        if ((-A) * q0 > p0 * B) {
          p0 = -A;
          q0 = B;
        }
      } else if (B < 0 && A > 0) {  // y/x < A/(-B) if B < 0
        if (A * q1 < p1 * (-B)) {
          p1 = A;
          q1 = -B;
        }
      }
    }
  }
  if (fail || p0 * q1 >= p1 * q0) {
    printf("IMPOSSIBLE\n");
  } else {
    auto pq = middle(p0, q0, p1, q1);
    printf("%d %d\n", pq.first, pq.second);
  }
}

Python

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
                break
            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 fail or p0 * q1 >= p1 * q0:
        return "IMPOSSIBLE"
    p, q = middle(p0, q0, p1, q1)
    return str(p) + " " + str(q)

To learn more about the properties and applications of the Stern–Brocot tree, see its main article.

Fractional Linear Transformations

Another important concept related to continued fractions is the fractional linear transformation.

Fractional Linear Transformation

A fractional linear transformation is a function L:R→RL:\mathbf R\rightarrow\mathbf R of the form

L(x)=ax+bcx+d,L(x) = \dfrac{ax+b}{cx+d},

where a,b,c,d∈Ra,b,c,d\in\mathbf R and ad−bc≠0ad-bc\neq 0.

About the Condition ad−bc≠0ad-bc\neq 0

It is easy to verify that when ad−bc=0ad-bc=0, the function may be undefined or constant.

Fractional linear transformations have the following properties:

Properties of Fractional Linear Transformations

Let L1,L2,L3L_1,L_2,L_3 be fractional linear transformations, and let the matrix formed by the coefficients of LiL_i be

Mi=(aibicidi)M_i=\begin{pmatrix}a_i & b_i \\ c_i & d_i\end{pmatrix}

Then they have the following properties:7

  1. The composition L1∘L2L_1\circ L_2 and inverse transformation L1−1L_1^{-1} of fractional linear transformations are still fractional linear transformations; in other words, all fractional linear transformations form a group;
  2. A fractional linear transformation is unchanged when all its coefficients are multiplied by the same nonzero constant: for any λ≠0\lambda\neq 0, if M2=λM1M_2=\lambda M_1, then L2=L1L_2=L_1;
  3. The coefficient matrix of the composition of fractional linear transformations is the product of their coefficient matrices: if M1M2=M3M_1M_2=M_3, then L1∘L2=L3L_1\circ L_2=L_3;
  4. The coefficient matrix of the inverse transformation of a fractional linear transformation is the inverse of its coefficient matrix: if M1−1=M2M_1^{-1}=M_2, then L1−1=L2L_1^{-1}=L_2.
Proof

Here we provide only the forms of the composition and inverse transformation of fractional linear transformations. Once these forms are obtained, all the properties are easy to verify.

The composition of fractional linear transformations L1L_1 and L2L_2:

L1∘L2=a1a2x+b2c2x+d2+b1c1a2x+b2c2x+d2+d1=(a1a2+b1c2)x+(a1b2+b1d2)(c1a2+d1c2)x+(c1b2+d1d2).\begin{aligned} L_1\circ L_2 &= \dfrac{a_1\dfrac{a_2x+b_2}{c_2x+d_2}+b_1}{c_1\dfrac{a_2x+b_2}{c_2x+d_2}+d_1} = \dfrac{(a_1a_2+b_1c_2)x+(a_1b_2+b_1d_2)}{(c_1a_2+d_1c_2)x+(c_1b_2+d_1d_2)}. \end{aligned}

The inverse transformation of the fractional linear transformation L1(x)L_1(x):

y=L1(x)=a1x+b1c1x+d1  ⟺  x=L1−1(y)=d1y−b1−c1y+a1.y = L_1(x) = \dfrac{a_1x+b_1}{c_1x+d_1} \iff x = L_1^{-1}(y) = \dfrac{d_1y - b_1}{-c_1y + a_1}.

A finite continued fraction [a0,a1,⋯ ,an][a_0,a_1,\cdots,a_n] can be viewed as the result of composing a sequence of fractional linear transformations. Let

Li(x)=aix+1x=[ai,x].L_i(x) = \dfrac{a_ix+1}{x} = [a_i,x].

Then the finite continued fraction

[a0,a1,⋯ ,an]=L0∘L1∘⋯Ln(∞).[a_0,a_1,\cdots,a_n] = L_0\circ L_1\circ \cdots L_n(\infty).

Here, the value of a fractional linear transformation L(x)=ax+bcx+dL(x)=\dfrac{ax+b}{cx+d} at x=∞x=\infty is ac\dfrac{a}{c}, the limit of the function as x→±∞x\rightarrow\pm\infty.

For a general continued fraction, let the remainder of the real number xx be rk+1r_{k+1}, that is, x=[a0,⋯ ,ak,rk+1]x=[a_0,\cdots,a_k,r_{k+1}]. Then

x=L0∘L1∘⋯Lk(rk+1)=pkrk+1+pk−1qkrk+1+qk−1.x = L_0\circ L_1\circ \cdots L_k(r_{k+1}) = \dfrac{p_kr_{k+1}+p_{k-1}}{q_kr_{k+1}+q_{k-1}}.

This also gives the form of the fractional linear transformation L0∘L1∘⋯∘LkL_0\circ L_1\circ\cdots\circ L_k.

The expression can of course also be verified directly. Initially,

x=x+00x+1=p−1x+p−2q−1x+q−2.x=\dfrac{x+0}{0x+1}=\dfrac{p_{-1}x+p_{-2}}{q_{-1}x+q_{-2}}.

Then, if L0∘L1∘⋯∘Lk−1L_0\circ L_1\circ\cdots\circ L_{k-1} has the form

pk−1x+pk−2qk−1x+qk−2\dfrac{p_{k-1}x+p_{k-2}}{q_{k-1}x+q_{k-2}}

the composition formula for fractional linear transformations gives

L0∘L1∘⋯∘Lk−1∘Lk=(pk−1ak+pk−2)x+pk−1(qk−1ak+qk−2)x+qk−1=pkx+pk−1qkx+qk−1.L_0\circ L_1\circ\cdots\circ L_{k-1}\circ L_k = \dfrac{(p_{k-1}a_k+p_{k-2})x+p_{k-1}}{(q_{k-1}a_k+q_{k-2})x+q_{k-1}} = \dfrac{p_kx+p_{k-1}}{q_kx+q_{k-1}}.

This inductively yields the form above. Fractional linear transformations also provide another perspective for understanding the recurrence formula and initial conditions.

DMOPC '19 Contest 7 P4 - Bob and Continued Fractions

Given a positive-integer array a1,⋯ ,ana_1,\cdots,a_n and mm queries, each query gives l≤rl\le r and asks for the value of [al,⋯ ,ar][a_l,\cdots,a_r].

Solution

Interpreting a continued fraction as the value at x=∞x=\infty of a composition of fractional linear transformations, we only need to be able to query the composition of a segment of fractional linear transformations many times. Since every fractional linear transformation can be inverted, we can preprocess prefix products and answer queries by taking differences, in O(n+m)O(n+m) time; if updates are needed, structures such as a segment tree can be used for storage.

C++

#include <algorithm>
#include <iostream>
#include <tuple>
#include <vector>

constexpr int M = 1e9 + 7;

// FLTs. Essentially 2x2 matrix.
struct FracLinearTrans {
  int mat[4];

  FracLinearTrans() : mat{} {}

  FracLinearTrans(int x) : mat{x, 1, 1, 0} {}

  FracLinearTrans(int a, int b, int c, int d) : mat{a, b, c, d} {}

  FracLinearTrans operator*(const FracLinearTrans& rhs) const {
    return FracLinearTrans(
        ((long long)mat[0] * rhs.mat[0] + (long long)mat[1] * rhs.mat[2]) % M,
        ((long long)mat[0] * rhs.mat[1] + (long long)mat[1] * rhs.mat[3]) % M,
        ((long long)mat[2] * rhs.mat[0] + (long long)mat[3] * rhs.mat[2]) % M,
        ((long long)mat[2] * rhs.mat[1] + (long long)mat[3] * rhs.mat[3]) % M);
  }

  FracLinearTrans inv() const {
    return FracLinearTrans(mat[3], M - mat[1], M - mat[2], mat[0]);
  }
};

int main() {
  int n, q;
  std::cin >> n >> q;
  // Get prefix sum of FLTs.
  std::vector<FracLinearTrans> ps(1, {1, 0, 0, 1});
  ps.reserve(n + 1);
  for (int i = 1; i <= n; ++i) {
    int a;
    std::cin >> a;
    ps[i] = ps[i - 1] * FracLinearTrans(a);
  }
  // Query.
  for (; q; --q) {
    int l, r;
    std::cin >> l >> r;
    // Difference.
    auto res = ps[l - 1].inv() * ps[r];
    int u = res.mat[0], d = res.mat[2];
    // Correct signs.
    if (!(l & 1)) {
      if (u) u = M - u;
      if (d) d = M - d;
    }
    printf("%d %d\n", u, d);
  }
  return 0;
}

Python

# PYTHON IS TOO SLOW TO PASS THIS PROBLEM.
# JUST FOR REFERENCE.
M = 10**9 + 7


def mul(a, b):
    return (
        (a[0] * b[0] + a[1] * b[2]) % M,
        (a[0] * b[1] + a[1] * b[3]) % M,
        (a[2] * b[0] + a[3] * b[2]) % M,
        (a[2] * b[1] + a[3] * b[3]) % M,
    )


def inv(a):
    return (a[3], M - a[1], M - a[2], a[0])


n, q = map(int, input().split())
ps = [(1, 0, 0, 1)]
# Get presum.
for a in map(int, input().split()):
    ps.append(mul(ps[-1], (a, 1, 1, 0)))
for _ in range(q):
    l, r = map(int, input().split())
    res = mul(inv(ps[l - 1]), ps[r])
    u, d = res[0], res[2]
    if l % 2 == 0:
        if u:
            u = M - u
        if d:
            d = M - d
    print(u, d)

Arithmetic Operations on Continued Fractions

Using fractional linear transformations, we can perform the four arithmetic operations on continued fractions. This algorithm was first proposed by Gosper.

The foundation of the algorithm is computing the fractional linear transformation of a continued fraction. This section uses finite continued fractions as an example, but because producing each output term only requires reading finitely many terms from the input continued fractions, it also applies to infinite continued fractions and can compute to arbitrary precision. Combined with the continued-fraction comparison algorithm above, it can exactly compare differences between real numbers to arbitrary precision.

Fractional Linear Transformation of a Continued Fraction

Given a fractional linear transformation L(x)=ax+bcx+dL(x)=\dfrac{ax+b}{cx+d} and a continued fraction α=[α0,α1,⋯ ,αn]\alpha=[\alpha_0,\alpha_1,\cdots,\alpha_n], find the continued-fraction representation [β0,β1,⋯ ,βm][\beta_0,\beta_1,\cdots,\beta_m] of β=L(α)\beta=L(\alpha).

Solution

The basic idea is to determine the values of βi\beta_i one by one. Define

Lγ(x)=γ+1x=γx+1x.L_\gamma(x) = \gamma+\dfrac{1}{x} = \dfrac{\gamma x+1}{x}.

Since

L(α)=L∘Lα0∘Lα1∘⋯∘Lαn(∞),L(\alpha) = L\circ L_{\alpha_0}\circ L_{\alpha_1}\circ \cdots \circ L_{\alpha_n}(\infty),

we can compute the value of L(α)L(\alpha) by successively composing LL with LαkL_{\alpha_k}. However, if we want the continued-fraction representation of L(α)L(\alpha), we do not need to compute the complete value of L(α)L(\alpha) and then find its continued-fraction representation. We can determine the values of β0,β1,⋯\beta_0,\beta_1,\cdots while composing the LαiL_{\alpha_i}.

For example, suppose that we have currently computed

L∘Lα0∘Lα1∘⋯∘Lαk(x)=akx+bkckx+dkL\circ L_{\alpha_0}\circ L_{\alpha_1}\circ \cdots \circ L_{\alpha_k}(x) = \dfrac{a_kx+b_k}{c_kx+d_k}

and ck,dkc_k,d_k have the same sign. Then L∘Lα0∘Lα1∘⋯∘Lαk(x)L\circ L_{\alpha_0}\circ L_{\alpha_1}\circ \cdots \circ L_{\alpha_k}(x) is monotone on [0,∞][0,\infty], and its value must lie between akck\dfrac{a_k}{c_k} and bkdk\dfrac{b_k}{d_k}. Therefore, if

⌊akck⌋=⌊bkdk⌋,\left\lfloor\dfrac{a_k}{c_k}\right\rfloor = \left\lfloor\dfrac{b_k}{d_k}\right\rfloor,

we can determine that this is the integer part β0\beta_0 of L∘Lα0∘Lα1∘⋯∘Lαk(x)L\circ L_{\alpha_0}\circ L_{\alpha_1}\circ \cdots \circ L_{\alpha_k}(x). Composing Lβ0−1L_{\beta_0}^{-1} on the left then gives

Lβ0−1∘L∘Lα0∘Lα1∘⋯∘Lαk.L_{\beta_0}^{-1}\circ L\circ L_{\alpha_0}\circ L_{\alpha_1}\circ \cdots \circ L_{\alpha_k}.

We can then continue adding Lαk+1,Lαk+2,⋯L_{\alpha_{k+1}},L_{\alpha_{k+2}},\cdots to determine the new integer part, namely β1\beta_1. Continuing in this way determines all the values βj\beta_j.

The algorithm requires cc and dd to have the same sign to ensure that the discontinuity of the function does not lie in [0,∞][0,\infty]. This is always possible because the definition of a simple continued fraction requires all coefficients other than α0\alpha_0 to be positive integers. It follows that cc and dd must have the same sign after finitely many steps, and will continue to do so thereafter.

In an implementation, we only need to maintain the coefficient matrix (abcd)\begin{pmatrix}a&b\\c&d\end{pmatrix} of the current fractional linear transformation and check whether cc and dd have the same sign and whether ac\dfrac{a}{c} and bd\dfrac{b}{d} have the same integer part. Right-composing with LαiL_{\alpha_i} gives (aαi+bacαi+dc)\begin{pmatrix}a\alpha_i+b&a\\ c\alpha_i+d&c\end{pmatrix}. If the two integer parts are both βj\beta_j, append βj\beta_j to the continued fraction of the result and left-compose with Lβj−1L_{\beta_j}^{-1}; this is equivalent to computing (cda mod cb mod d)\begin{pmatrix}c&d\\ a\bmod c & b \bmod d \end{pmatrix}.

The fractional linear transformation of a continued fraction can already be used to compute arithmetic operations between fractions and continued fractions:

pq±x=±qx+p0x+q, pqx=px+00x+q, pq/x=0x+pqx+0.\dfrac{p}{q}\pm x = \dfrac{\pm qx+p}{0x+q},\ \dfrac{p}{q}x = \dfrac{px+0}{0x+q},\ \frac{p}{q}/x = \dfrac{0x+p}{qx+0}.

Arithmetic operations between general continued fractions require a bi-fractional linear transformation:

x+y=0xy+x+y+00xy+0x+0y+1, xy=1xy+0x+0y+00xy+0x+0y+1, xy=0xy+x+0y+00xy+0x+y+0.x+y = \dfrac{0xy+x+y+0}{0xy+0x+0y+1},\ xy = \dfrac{1xy+0x+0y+0}{0xy+0x+0y+1},\ \dfrac{x}{y} = \dfrac{0xy+x+0y+0}{0xy+0x+y+0}.
Bi-Fractional Linear Transformation of Continued Fractions

Given a bi-fractional linear transformation L(x,y)=axy+bx+cy+dexy+fx+gy+hL(x,y)=\dfrac{axy+bx+cy+d}{exy+fx+gy+h} and continued fractions α=[α0,α1,⋯ ,αn]\alpha=[\alpha_0,\alpha_1,\cdots,\alpha_n] and β=[β0,β1,⋯ ,βm]\beta=[\beta_0,\beta_1,\cdots,\beta_m], find the continued-fraction representation [γ0,γ1,⋯ ,γℓ][\gamma_0,\gamma_1,\cdots,\gamma_\ell] of γ=L(α,β)\gamma=L(\alpha,\beta).

Solution

As in the single-variable fractional linear transformation case, to determine the integer part we only need to ensure that the integer part of the current fractional linear transformation remains unchanged over (x,y)∈[0,∞]×[0,∞](x,y)\in[0,\infty]\times[0,\infty], that is, e,f,g,he,f,g,h all have the same sign and

⌊ae⌋=⌊bf⌋=⌊cg⌋=⌊dh⌋.\left\lfloor\dfrac{a}{e}\right\rfloor = \left\lfloor\dfrac{b}{f}\right\rfloor = \left\lfloor\dfrac{c}{g}\right\rfloor = \left\lfloor\dfrac{d}{h}\right\rfloor.

Right composition is replaced by computing L(x,y)↦L(Lαi(x),y)L(x,y)\mapsto L(L_{\alpha_i}(x),y) and L(x,y)↦L(x,Lβj(y))L(x,y)\mapsto L(x,L_{\beta_j}(y)), which likewise can be represented as a linear transformation of the coefficients. Left composition is exactly the same as in the single-variable case; it only requires taking remainders.

Compared with the single-variable case, the two-variable case must decide whether to compose LαiL_{\alpha_i} or LβjL_{\beta_j} first. Since the order of composition does not affect the final result, the order can be chosen freely, for example by composing LαiL_{\alpha_i} and LβjL_{\beta_j} alternately. Alternatively, use the heuristic of composing first in the dimension with the larger difference between ratios: if ∣bf−dh∣>∣cg−dh∣\left|\dfrac{b}{f}-\dfrac{d}{h}\right|>\left|\dfrac{c}{g}-\dfrac{d}{h}\right|, compose LαiL_{\alpha_i} first; otherwise, compose LβjL_{\beta_j} first.

Periodic Continued Fractions

As with repeating decimals, if the coefficients of a continued fraction form a repeating sequence, it is called a periodic continued fraction.

Periodic Continued Fraction

Let x=[a0,a1,a2,⋯ ]x=[a_0,a_1,a_2,\cdots] be a continued fraction, and suppose there are a natural number KK and a positive integer LL such that ak=ak+La_k=a_{k+L} for every k≥Kk\ge K. Then xx is called a periodic continued fraction. The smallest LL satisfying this condition is called its least positive period, and the sequence ak,⋯ ,ak+L−1a_{k},\cdots,a_{k+L-1} that repeats in the continued fraction is called its period. Using the period, a periodic continued fraction can be written as x=[a0,⋯ ,ak−1,ak,⋯ ,ak+L−1‾]x=[a_0,\cdots,a_{k-1},\overline{a_k,\cdots,a_{k+L-1}}]. If KK can be chosen to be 00, that is, x=[a0,⋯ ,aL−1‾]x=[\overline{a_0,\cdots,a_{L-1}}], it is called a purely periodic continued fraction; otherwise it is called an eventually periodic continued fraction.

Quadratic Irrationals

A concept closely related to periodic continued fractions is the real quadratic irrational (quadratic irrational), that is, an irrational solution of a quadratic equation with integer coefficients. Every quadratic irrational can be written in the form

a+bDa+b\sqrt D

where a,ba,b are rational numbers and DD is a positive square-free integer. Quadratic irrationals mentioned in this article are assumed to be real. The conjugate of a+bDa+b\sqrt D means a−bDa-b\sqrt{D}.

Euler's result states that every periodic continued fraction is a quadratic irrational.

Theorem (Euler)

Every number represented by a periodic continued fraction is a quadratic irrational.

Proof

For a general periodic continued fraction x=[a0,⋯ ,ak−1,ak,⋯ ,ak+L−1‾]x=[a_0,\cdots,a_{k-1},\overline{a_k,\cdots,a_{k+L-1}}], let y=[ak,⋯ ,ak+L−1‾]y=[\overline{a_k,\cdots,a_{k+L-1}}]. Then

x=[a0,⋯ ,ak−1,y]=L0(y),y=[ak,⋯ ,ak+L−1,y]=L1(y),\begin{aligned} x&=[a_0,\cdots,a_{k-1},y] = L_0(y),\\ y&=[a_k,\cdots,a_{k+L-1},y] = L_1(y), \end{aligned}

where both L0(⋅)L_0(\cdot) and L1(⋅)L_1(\cdot) are fractional linear transformations. Hence, xx satisfies

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

Suppose the fractional linear transformation L0∘L1∘L0−1(x)=ax+bcx+dL_0\circ L_1\circ L_0^{-1}(x) = \dfrac{ax+b}{cx+d}. Then xx satisfies

cx2+(d−a)x−b=0.cx^2+(d-a)x-b=0.

Therefore, every periodic continued fraction is a solution of a quadratic equation with integer coefficients. Since every infinite continued fraction is irrational, periodic continued fractions represent quadratic irrationals.

Lagrange's result shows that the converse also holds, so quadratic irrationals and periodic continued fractions are equivalent.

Theorem (Lagrange)

Every quadratic irrational can be represented as a periodic continued fraction.

Proof

The idea is to prove that the remainders eventually repeat. Suppose the quadratic irrational xx can be written as

x=P0+DQ0x = \dfrac{P_0+\sqrt{D}}{Q_0}

where P0,Q0,DP_0,Q_0,D are integers and Q0∣D−P02Q_0\mid D-P_0^2. This is always possible. For example, any quadratic irrational xx can be written as

a+bD′=paqa+pbqbD′=paqb+pbqaD′qaqb=papbqaqb+(qaqb)2D′(qaqb)2a+b\sqrt{D'} = \dfrac{p_a}{q_a}+\dfrac{p_b}{q_b}\sqrt{D'} = \dfrac{p_aq_b+p_bq_a\sqrt{D'}}{q_aq_b} = \dfrac{p_ap_bq_aq_b+\sqrt{(q_aq_b)^2D'}}{(q_aq_b)^2}

Then set P=papbqaqbP=p_ap_bq_aq_b, Q=(qaqb)2Q=(q_aq_b)^2, and D=QD′D=QD'.

The advantage of writing it in this form is that all its remainders can be shown to have a similar form:

rk=Pk+DQk,r_k=\dfrac{P_k+\sqrt D}{Q_k},

where Pk,QkP_k,Q_k are integers and Qk∣D−Pk2Q_k\mid D-P_k^2. The condition Qk∣D−Pk2Q_k\mid D-P_k^2 ensures that the coefficient before D\sqrt{D} in the numerator of every remainder is 11.

We can obtain the form of the remainders by mathematical induction. The case k=0k=0 is clear. Assume that the form of rkr_k has been obtained, and let ak=⌊rk⌋a_k=\lfloor r_k\rfloor. Then

rk=ak+1rk+1.r_k = a_k+\dfrac{1}{r_{k+1}}.

Suppose rk+1r_{k+1} also has the analogous form, and substitute it together with rkr_k into the equation above:

Pk+DQk=ak+Qk+1Pk+1+D=ak+Qk+1Pk+1−Qk+1DPk+12−D.\dfrac{P_k+\sqrt D}{Q_k} = a_k + \dfrac{Q_{k+1}}{P_{k+1}+\sqrt{D}} = a_k + \dfrac{Q_{k+1}P_{k+1}-Q_{k+1}\sqrt{D}}{P_{k+1}^2-D}.

Since the representation of a quadratic irrational as a+bDa+b\sqrt{D} is unique, comparing the coefficients on both sides gives

PkQk=ak+Qk+1Pk+1Pk+12−D, 1Qk=−Qk+1Pk+12−D.\dfrac{P_k}{Q_k} = a_k+\dfrac{Q_{k+1}P_{k+1}}{P_{k+1}^2-D},\ \dfrac{1}{Q_k}=-\dfrac{Q_{k+1}}{P_{k+1}^2-D}.

Substituting the second equation into the first lets us solve for Pk+1P_{k+1}:

PkQk=ak−Pk+1Qk  ⟺  Pk+1=akQk−Pk.\dfrac{P_k}{Q_k} = a_k-\dfrac{P_{k+1}}{Q_k} \iff P_{k+1} = a_kQ_k-P_k.

Substituting into the second equation then gives Qk+1Q_{k+1}:

Qk+1=D−Pk+12Qk=D−(akQk−Pk)2Qk=−ak2Qk+2akPk+D−Pk2Qk.Q_{k+1} = \dfrac{D-P_{k+1}^2}{Q_k} = \dfrac{D-(a_kQ_k-P_k)^2}{Q_k} = -a_k^2Q_k+2a_kP_k+\dfrac{D-P_k^2}{Q_k}.

By the induction hypothesis, Qk∣D−Pk2Q_k\mid D-P_k^2, so Pk+1P_{k+1} and Qk+1Q_{k+1} are indeed integers, meaning that rk+1r_{k+1} also has the required form.

Finally, we prove that the remainders can take only finitely many values and therefore must repeat. We obtained earlier that

Pk+DQk=rk=−qk−2x−pk−2qk−1x−pk−1\dfrac{P_k+\sqrt{D}}{Q_k} = r_k = -\dfrac{q_{k-2}x-p_{k-2}}{q_{k-1}x-p_{k-1}}

and for an irrational number, we always have rk>1r_k>1. Its conjugate is

Pk−DQk=rk∗=−qk−2x∗−pk−2qk−1x∗−pk−1=−qk−2qk−1x∗−pk−2qk−2x∗−pk−1qk−1\dfrac{P_k-\sqrt{D}}{Q_k} = r_k^* = -\dfrac{q_{k-2}x^*-p_{k-2}}{q_{k-1}x^*-p_{k-1}} = -\dfrac{q_{k-2}}{q_{k-1}}\dfrac{x^*-\dfrac{p_{k-2}}{q_{k-2}}}{x^*-\dfrac{p_{k-1}}{q_{k-1}}}

For sufficiently large kk, this must be less than 00, because

qk−2qk−1>0, lim⁡k→∞x∗−pk−2qk−2x∗−pk−1qk−1=x∗−xx∗−x=1.\dfrac{q_{k-2}}{q_{k-1}}>0,\ \lim_{k\rightarrow\infty}\dfrac{x^*-\dfrac{p_{k-2}}{q_{k-2}}}{x^*-\dfrac{p_{k-1}}{q_{k-1}}}=\dfrac{x^*-x}{x^*-x}=1.

This shows that

2DQk=rk−rk∗>1  ⟺  0<Qk≤2D.\dfrac{2\sqrt{D}}{Q_k} = r_k-r_k^*>1 \iff 0<Q_k\le 2\sqrt{D}.

Therefore, QkQ_k can take only finitely many values. Consequently,

D−Pk2=QkQk−1>0  ⟺  ∣Pk∣<D,D-P_{k}^2=Q_kQ_{k-1}>0 \iff |P_k|<\sqrt{D},

Therefore, PkP_k can also take only finitely many values. Consequently, the remainder rkr_k has only finitely many possible values, so some value must repeat within infinitely many terms.

The proof of the theorem also gives a recurrence for computing the remainders of a quadratic irrational:

Recurrence for the remainders of a quadratic irrational

Every quadratic irrational can be written in the form

x=P0+DQ0x=\dfrac{P_0+\sqrt{D}}{Q_0}

where Q0∣D−P02Q_0\mid D-P^2_0. For its remainder

rk=Pk+DQkr_{k}=\dfrac{P_k+\sqrt{D}}{Q_k}

Pk,QkP_k,Q_k are integers satisfying the recurrence

Pk+1=akQk−Pk,Qk+1=D−Pk+12Qk.\begin{aligned} P_{k+1} &= a_kQ_k-P_k,\\ Q_{k+1} &= \dfrac{D-P_{k+1}^2}{Q_k}. \end{aligned}

This recurrence can be used directly to compute the continued fraction of a quadratic irrational. According to the proof of the theorem, ∣Pk∣<D|P_k|<\sqrt{D} and Qk≤2DQ_k\le 2\sqrt{D}. The algorithm's complexity depends on the length of the period, which can be shown to be O(Dlog⁡D)O(\sqrt{D}\log D)8.

Quadratic irrational

Given a quadratic irrational α=x+ynz\alpha=\dfrac{x+y\sqrt{n}}{z}, find its continued-fraction representation. Here x,y,z,n∈Zx,y,z,n\in\mathbf Z and n>0n>0 is not a perfect square.

Solution

First rewrite the quadratic irrational in the form above, and then compute it using the recurrence. The terms of the continued fraction are given by ak=⌊rk⌋a_k=\lfloor r_k\rfloor. To find the period, store the index at which each pair (Pk,Qk)(P_k,Q_k) first appears.

C++

// Return the continued fraction and minimal positive period
//   of a quadratic irrational (x + y * sqrt(n)) / z.
auto quadratic_irrational(int x, int y, int z, int n) {
  int p = x * z;
  int d = n * y * y * z * z;
  int q = z * z;
  int dd = (int)sqrt(n) * y * z;
  int i = 0;
  std::vector<int> a;
  std::unordered_map<size_t, int> used;
  while (!used.count(((1LL << 32) * p) | q)) {
    a.emplace_back((p + dd) / q);
    used[((1LL << 32) * p) | q] = i++;
    p = a.back() * q - p;
    q = (d - p * p) / q;
  }
  return std::make_pair(a, i - used[((1LL << 32) * p) | q]);
}

Python

# Return the continued fraction and minimal positive period
#   of a quadratic irrational (x + y * sqrt(n)) / z.
def quadratic_irrational(x, y, z, n):
    p = x * z
    d = n * y * y * z * z
    q = z * z
    dd = floor(sqrt(n)) * y * z
    i = 0
    a = []
    used = dict()
    while (p, q) not in used:
        a.append((p + dd) // q)
        used[p, q] = i
        p = a[-1] * q - p
        q = (d - p * p) // q
        i += 1
    return a, i - used[p, q]
Tavrida NU Akai Contest - Continued Fraction

Given xx and kk, where xx is not a perfect square and 0≤k≤1090\le k\le 10^9, find the kk-th convergent xkx_k of x\sqrt{x}.

Solution

First use the algorithm above to find the period of x\sqrt{x}. Expressing the period as a fractional linear transformation allows us to obtain xkx_k using binary exponentiation. The parts before the period and the part shorter than one full period must of course be handled separately.

C++

#include <algorithm>
#include <cmath>
#include <iostream>
#include <tuple>
#include <unordered_map>
#include <vector>

// Return the continued fraction and minimal positive period
//   of a quadratic irrational (x + y * sqrt(n)) / z.
auto quadratic_irrational(int x, int y, int z, int n) {
  int p = x * z;
  int d = n * y * y * z * z;
  int q = z * z;
  int dd = (int)sqrt(n) * y * z;
  int i = 0;
  std::vector<int> a;
  std::unordered_map<size_t, int> used;
  while (!used.count(((1LL << 32) * p) | q)) {
    a.emplace_back((p + dd) / q);
    used[((1LL << 32) * p) | q] = i++;
    p = a.back() * q - p;
    q = (d - p * p) / q;
  }
  return std::make_pair(a, i - used[((1LL << 32) * p) | q]);
}

// Fractional Linear Transformation.
struct FracLinearTrans {
  static constexpr int M = 1e9 + 7;
  int mat[4];

  FracLinearTrans(int a, int b, int c, int d) : mat{a, b, c, d} {}

  FracLinearTrans operator*(const FracLinearTrans& rhs) const {
    return FracLinearTrans(
        ((long long)mat[0] * rhs.mat[0] + (long long)mat[1] * rhs.mat[2]) % M,
        ((long long)mat[0] * rhs.mat[1] + (long long)mat[1] * rhs.mat[3]) % M,
        ((long long)mat[2] * rhs.mat[0] + (long long)mat[3] * rhs.mat[2]) % M,
        ((long long)mat[2] * rhs.mat[1] + (long long)mat[3] * rhs.mat[3]) % M);
  }
};

int main() {
  int x, k, L;
  std::cin >> x >> k;
  std::vector<int> a;
  std::tie(a, L) =
      quadratic_irrational(0, 1, 1, x);  // L==a.size()-1 for sqrt(x)
  FracLinearTrans cyc(1, 0, 0, 1);
  for (int i = a.size() - 1; i; --i) {
    cyc = FracLinearTrans(a[i], 1, 1, 0) * cyc;
  }
  // 1/0=Inf.
  FracLinearTrans res(0, 1, 0, 0);
  // Tail terms.
  for (int i = k % L; i; --i) {
    res = FracLinearTrans(a[i], 1, 1, 0) * res;
  }
  // Binary exponentiation.
  for (int b = k / L; b; b >>= 1) {
    if (b & 1) res = cyc * res;
    cyc = cyc * cyc;
  }
  // First term.
  res = FracLinearTrans(a[0], 1, 1, 0) * res;
  printf("%d/%d", res.mat[1], res.mat[3]);
  return 0;
}

Python

from math import sqrt, floor


# Return the continued fraction and minimal positive period
#   of a quadratic irrational (x + y * sqrt(n)) / z.
def quadratic_irrational(x, y, z, n):
    p = x * z
    d = n * y * y * z * z
    q = z * z
    dd = floor(sqrt(n)) * y * z
    i = 0
    a = []
    used = dict()
    while (p, q) not in used:
        a.append((p + dd) // q)
        used[p, q] = i
        p = a[-1] * q - p
        q = (d - p * p) // q
        i += 1
    return a, i - used[p, q]


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


# Binary exponentiation.
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)
    )


mod = 10**9 + 7
x, k = map(int, input().split())
a, T = quadratic_irrational(0, 1, 1, x)

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

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

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

Purely periodic continued fractions

A quadratic irrational has a periodic continued-fraction representation if and only if it is a quadratic irrational; this section gives the necessary and sufficient condition for a real number to have a purely periodic continued-fraction representation.

First, because a purely periodic continued fraction has a form similar to that of a finite continued fraction, we can perform a “reversal” operation. As with the reversal theorem, the continued-fraction representation obtained this way has a definite relationship with the original representation.

Theorem (Galois)

For the purely periodic continued fraction

x=[a0,a1,⋯ ,aℓ‾],x = \left[\overline{a_0,a_1,\cdots,a_{\ell}}\right],

define

x′=[aℓ,⋯ ,a1,a0‾].x' = \left[\overline{a_{\ell},\cdots,a_1,a_0}\right].

Then xx and x′x' are “reciprocal negative conjugates” of each other; that is, x′x' is the negative reciprocal of the conjugate of xx.

Proof

Since ℓ+1\ell+1 is not required to be the minimal positive period, we may assume without loss of generality that ℓ>0\ell>0. By the reversal theorem,

pℓpℓ−1=[aℓ,⋯ ,a1,a0]=pℓ′qℓ′,qℓqℓ−1=[aℓ,⋯ ,a1]=pℓ−1′qℓ−1′.\begin{aligned} \dfrac{p_\ell}{p_{\ell-1}} &= [a_\ell,\cdots,a_1,a_0] = \dfrac{p'_\ell}{q'_\ell},\\ \dfrac{q_\ell}{q_{\ell-1}} &= [a_\ell,\cdots,a_1] = \dfrac{p'_{\ell-1}}{q'_{\ell-1}}. \end{aligned}

Since both sides of each equality are reduced fractions,

pℓ′=pℓ, qℓ′=pℓ−1, pℓ−1′=qℓ, qℓ−1′=qℓ−1.p'_\ell = p_\ell,\ q'_\ell = p_{\ell-1},\ p'_{\ell-1}=q_\ell,\ q'_{\ell-1} = q_{\ell-1}.

For the purely periodic continued fraction xx, its ℓ+1\ell+1-st remainder is xx itself. Therefore,

x=xpℓ+pℓ−1xqℓ+qℓ−1.x = \dfrac{xp_\ell+p_{\ell-1}}{xq_\ell+q_{\ell-1}}.

Thus it satisfies the quadratic equation

qℓx2+(qℓ−1−pℓ)x−pℓ−1=0.q_\ell x^2+(q_{\ell-1}-p_\ell)x-p_{\ell-1} = 0.

Similarly, x′x' satisfies

qℓ′(x′)2+(qℓ−1′−pℓ′)x′−pℓ−1′=0.q'_\ell(x')^2+(q'_{\ell-1}-p'_\ell)x'-p'_{\ell-1} = 0.

Using the relationships among the coefficients, this equation can be written as

pℓ−1(x′)2+(qℓ−1−pℓ)x′−qℓ=0.p_{\ell-1}(x')^2+(q_{\ell-1}-p_\ell)x'-q_\ell = 0.

Let y=−1x′y=-\dfrac{1}{x'}. Then xx and yy satisfy the same equation. However, x>0>yx>0>y, so they are not the same root; they are conjugates of each other, proving the proposition.

Using this observation, Galois further gave a necessary and sufficient condition for a quadratic irrational to have a purely periodic continued-fraction representation.

Theorem (Galois)

A quadratic irrational xx can be represented as a purely periodic continued fraction if and only if x>1x>1 and its conjugate satisfies −1<x∗<0-1<x^*<0.

Proof

If xx is a purely periodic continued fraction, then using the notation above, a0=aℓ+1≥1a_0=a_{\ell+1}\ge 1, so x>1x>1. Its reciprocal negative conjugate is also a continued fraction, so its conjugate x∗x^* satisfies −1x∗>1-\dfrac{1}{x^*}>1, or equivalently −1<x∗<0-1<x^*<0. This proves that every purely periodic continued fraction satisfies the condition.

Conversely, suppose that the quadratic irrational x>1x>1 satisfies −1<x∗<0-1<x^*<0. For the remainders rkr_k of xx, we have

rk=ak+1rk+1.r_k = a_k+\dfrac{1}{r_{k+1}}.

Both sides are quadratic irrationals, so taking conjugates gives

rk∗=ak+1rk+1∗.r_{k}^* = a_k+\dfrac{1}{r_{k+1}^*}.

Using this recurrence, we can prove that −1<rk∗<0-1<r_{k}^*<0 holds for every k≥0k\ge 0.

For k=0k=0, we have −1<r0∗=x0∗<0-1<r_0^*=x_0^*<0, which is clear. For k≥0k\ge 0, the definition of a simple continued fraction and x>1x>1 imply that ak≥1a_k\ge 1. Therefore, assuming −1<rk∗<0-1<r_k^*<0, we obtain

−1<−1ak<rk+1∗=1rk∗−ak<−11+ak<0.-1<-\dfrac{1}{a_k}< r_{k+1}^* = \dfrac{1}{r_k^*-a_k} < -\dfrac{1}{1+a_k} < 0.

This proves inductively that −1<rk∗<0-1<r_{k}^*<0 holds for every k≥0k\ge 0. Hence,

ak=−1rk+1∗+rk∗=⌊−1rk+1∗⌋.a_k = -\dfrac{1}{r_{k+1}^*}+r_k^* = \left\lfloor-\dfrac{1}{r_{k+1}^*}\right\rfloor.

Since every quadratic irrational has a periodic continued fraction, there is a positive integer LL and some sufficiently large kk such that rk=rk+Lr_{k}=r_{k+L}. But then necessarily

ak−1=⌊−1rk∗⌋=⌊−1rk+L∗⌋=ak+L−1.a_{k-1} = \left\lfloor-\dfrac{1}{r_{k}^*}\right\rfloor = \left\lfloor-\dfrac{1}{r_{k+L}^*}\right\rfloor = a_{k+L-1}.

Consequently,

rk−1=ak−1+1rk=ak+L−1+1rk+L=rk+L−1.r_{k-1} = a_{k-1}+\dfrac{1}{r_k} = a_{k+L-1}+\dfrac{1}{r_{k+L}} = r_{k+L-1}.

This means that the smallest kk for which rk=rk+Lr_{k}=r_{k+L} holds must be 00. In other words, xx can be represented as a purely periodic continued fraction.

Galois's theorem reveals the pattern in the continued-fraction representation of pure quadratic surds—quadratic irrationals of the form r\sqrt{r}.

Corollary

For a rational number r>1r>1, if r\sqrt{r} is irrational, then

r=[⌊r⌋,a1,⋯ ,aℓ,2⌊r⌋‾]\sqrt{r} = [\lfloor\sqrt{r}\rfloor,\overline{a_1,\cdots,a_{\ell},2\lfloor\sqrt{r}\rfloor}]

and for every 1≤k≤ℓ1\le k\le\ell, ak=aℓ+1−ka_k = a_{\ell+1-k}.

Proof

For the quadratic irrational r\sqrt{r}, since ⌊r⌋+r>1\lfloor\sqrt{r}\rfloor+\sqrt{r}>1 and −1<⌊r⌋−r<0-1<\lfloor\sqrt{r}\rfloor-\sqrt{r}<0, ⌊r⌋+r\lfloor\sqrt{r}\rfloor+\sqrt{r} is a purely periodic continued fraction:

⌊r⌋+r=[2⌊r⌋,a1,⋯ ,aℓ‾].\lfloor\sqrt{r}\rfloor+\sqrt{r} = [\overline{2\lfloor\sqrt{r}\rfloor,a_1,\cdots,a_\ell}].

According to the theorem above, its reciprocal negative conjugate has the form

1r−⌊r⌋=[aℓ,⋯ ,a1,2⌊r⌋‾].\dfrac{1}{\sqrt{r}-\lfloor\sqrt{r}\rfloor} = [\overline{a_\ell,\cdots,a_1,2\lfloor\sqrt{r}\rfloor}].

Using the basic properties of continued fractions, we obtain

r=⌊r⌋+11r−⌊r⌋=[⌊r⌋,aℓ,⋯ ,a1,2⌊r⌋‾].\sqrt{r}=\lfloor\sqrt{r}\rfloor+\dfrac{1}{\dfrac{1}{\sqrt{r}-\lfloor\sqrt{r}\rfloor}}=[\lfloor\sqrt{r}\rfloor,\overline{a_\ell,\cdots,a_1,2\lfloor\sqrt{r}\rfloor}].

On the other hand, the continued-fraction representation of ⌊r⌋+r\lfloor\sqrt{r}\rfloor+\sqrt{r} also gives

r=−⌊r⌋+(⌊r⌋+r)=[⌊r⌋,a1,⋯ ,aℓ,2⌊r⌋‾].\sqrt{r} = -\lfloor\sqrt{r}\rfloor+\left(\lfloor\sqrt{r}\rfloor+\sqrt{r}\right) = [\lfloor\sqrt{r}\rfloor,\overline{a_1,\cdots,a_\ell,2\lfloor\sqrt{r}\rfloor}].

Since the continued-fraction representation of an irrational number is unique, comparing the intermediate coefficients shows that ak=aℓ+1−ka_k=a_{\ell+1-k} for every 1≤k≤ℓ1\le k\le\ell.

Example: The continued-fraction expansion of 74\sqrt{74}

The continued fraction of 74\sqrt{74} can be computed as follows (this is only for illustration; programmatic computation should use the recursive algorithm mentioned above):

74=8+(−8)+74=[8,8+7410]=[8,1+−2+7410]=[8,1,2+747]=[8,1,1+−5+747]=[8,1,1,5+747]=[8,1,1,1+−2+747]=[8,1,1,1,2+7410]=[8,1,1,1,1+−8+7410]=[8,1,1,1,1,8+74]=[8,1,1,1,1,16+(−8)+74]=[8,1,1,1,1,16‾]\begin{aligned} \sqrt{74}&=8+(-8)+\sqrt{74}=\left[8,\frac{8+\sqrt{74}}{10}\right]\\ &=\left[8,1+\frac{-2+\sqrt{74}}{10}\right]=\left[8,1,\frac{2+\sqrt{74}}{7}\right]\\ &=\left[8,1,1+\frac{-5+\sqrt{74}}{7}\right]=\left[8,1,1,\frac{5+\sqrt{74}}{7}\right]\\ &=\left[8,1,1,1+\frac{-2+\sqrt{74}}{7}\right]=\left[8,1,1,1,\frac{2+\sqrt{74}}{10}\right]\\ &=\left[8,1,1,1,1+\frac{-8+\sqrt{74}}{10}\right]=\left[8,1,1,1,1,8+\sqrt{74}\right]\\ &=\left[8,1,1,1,1,16+(-8)+\sqrt{74}\right]=\left[8,\overline{1,1,1,1,16}\right] \end{aligned}

The remainders are:

r1=8+7410=[1,1,1,1,16‾]r2=2+747=[1,1,1,16,1‾]r3=5+747=[1,1,16,1,1‾]r4=2+7410=[1,16,1,1,1‾]r5=8+74=[16,1,1,1,1‾]\begin{alignedat}{3} r_1&=\frac{8+\sqrt{74}}{10}&&=\left[\overline{1,1,1,1,16}\right]\\ r_2&=\frac{2+\sqrt{74}}{7}&&=\left[\overline{1,1,1,16,1}\right]\\ r_3&=\frac{5+\sqrt{74}}{7}&&=\left[\overline{1,1,16,1,1}\right]\\ r_4&=\frac{2+\sqrt{74}}{10}&&=\left[\overline{1,16,1,1,1}\right]\\ r_5&=8+\sqrt{74}&&=\left[\overline{16,1,1,1,1}\right] \end{alignedat}

According to Galois's conclusion, the periodic parts of the remainders rkr_k and rL+1−kr_{L+1-k} are exact reversals, so they are reciprocal negative conjugates of each other. If the period length LL of D\sqrt{D} is odd, the middle term is its own reciprocal negative conjugate; if the period length LL is even, no such term exists. The discussion in the section on Pell equations will show that the parity of the period length determines whether the equation x2−Dy2=−1x^2-Dy^2=-1 has a solution.

The continued-fraction expansion of the quadratic irrational D\sqrt{D} is mainly used to solve Pell equations.

Examples

After mastering the basic concepts, we need to study some concrete examples to understand how continued fractions are applied in algorithmic competitions.

Offline convex hull

Given r=[a0,a1,⋯ ,an]r=[a_0,a_1,\cdots,a_n], find the convex hull of the set of lattice points (x,y)(x,y) satisfying 0≤x≤N0\le x\le N and 0≤y≤rx0\le y\le rx.

Solution

For the unbounded set x≥0x\ge 0, the upper convex hull is the line y=rxy=rx itself. However, as shown below, if we also require x≤Nx\le N, the upper convex hull eventually deviates from the line.

Figure: lattice hull

Starting from (0,0)(0,0), we can find all lattice points on the upper convex hull from left to right. Suppose that the last lattice point of the upper convex hull found so far is (x,y)(x,y). We now want to find the next lattice point (x′,y′)(x',y'). The vertex (x′,y′)(x',y') is to the upper right of (x,y)(x,y); let (Δx,Δy)=(x′−x,y′−y)(\Delta x,\Delta y)=(x'-x,y'-y) be their difference. Then necessarily

0<Δx≤N−x, 0≤Δy≤rΔx.0<\Delta x\le N-x,\ 0\le \Delta y\le r\Delta x.

The second inequality holds because the condition Δy>rΔx\Delta y>r\Delta x contradicts the fact that (x,y)(x,y) is already on the upper convex hull. Looking at the conditions that (Δx,Δy)(\Delta x,\Delta y) must satisfy, for different points (x,y)(x,y) only the upper bound on Δx\Delta x changes. Therefore, once this subproblem can be solved, all the lattice points in the original problem can be found recursively.

Let us then consider how to solve the subproblem. Compared with the original problem, the subproblem changes the upper bound of x to N′N' and asks for the first lattice point adjacent to the origin on the upper convex hull. Let the solution to the subproblem be (q,p)(q,p). Then pp and qq must be coprime (otherwise this would not be the first lattice point), and the slope pq\dfrac{p}{q} of the line from the origin is the largest among all lattice points below the line y=rxy=rx whose xx-coordinate does not exceed N′N' (otherwise it would not lie on the convex hull). According to the geometric interpretation above, such a point (x,y)(x,y) must correspond to a lower intermediate convergent of rr. Since a lower intermediate convergent with a larger denominator is closer to rr, the subproblem's solution (q,p)(q,p) corresponds to the lower intermediate convergent with the largest denominator among all lower intermediate convergents whose denominators do not exceed N′N'.

In an actual solution, there is no need to recompute this lower intermediate convergent for every subproblem. We should first compute all convergents, which provides a way to traverse all lower intermediate convergents. Then traverse the lower intermediate convergents in decreasing order of denominator, trying each time to add it to the previous lattice point (x,y)(x,y), and continue until it can no longer be added before trying the next lower intermediate convergent.

There are several obvious optimizations. First, for a lower intermediate convergent (q,p)(q,p), there must be an odd kk and 0≤t<ak0\le t<a_k such that (q,p)=(qk−1,pk−1)+t(qk,pk)(q,p)=(q_{k-1},p_{k-1})+t(q_k,p_k). It is enough to find the largest tt satisfying qk−1+tqk+x≤Nq_{k-1}+tq_k+x\le N, namely t=⌊N−qk−1−xqk⌋t=\left\lfloor\dfrac{N-q_{k-1}-x}{q_k}\right\rfloor. There is no need to worry about tt going out of range, because the larger lower convergent (qk+2,pk+2)(q_{k+2},p_{k+2}) has already been added. Each time the number of additions is determined, we can directly compute ⌊N−xq⌋\left\lfloor\dfrac{N-x}{q}\right\rfloor instead of trying them one by one.

The optimized algorithm has complexity O(n)O(n). Although a lower intermediate convergent may correspond to many lattice points, not many of them actually become increments. We now show that among all lower intermediate convergents (q,p)=(qk−1,pk−1)+t(qk,pk)(q,p)=(q_{k-1},p_{k-1})+t(q_k,p_k) with 0≤t<ak0\le t<a_k, at most two increments can occur. Suppose that an increment does occur among these lower intermediate convergents. Then necessarily qk−1≤N−x<qk+1q_{k-1}\le N-x<q_{k+1}. Set t=⌊N−qk−1−xqk⌋t=\left\lfloor\dfrac{N-q_{k-1}-x}{q_k}\right\rfloor. If t=0t=0, then the increment has Δx=qk−1\Delta x=q_{k-1}, so after adding the increment we have N−x′<qk−1N-x'<q_{k-1}, and no new increment can occur among these lower intermediate convergents. If t>0t>0, then after adding the increment we necessarily have N−x′=(N−qk−1−x) mod qk<qkN-x'=(N-q_{k-1}-x)\bmod q_k<q_k; even if another increment occurs in the same interval of lower intermediate convergents, the next one can only have t′=0t'=0. Thus, at most two increments can occur in such an interval of lower intermediate convergents. This proves that the total time complexity is O(n)O(n).

C++

// Find [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(std::vector<int> a, int N) {
  std::vector<int> p, q;
  std::tie(p, q) = convergents(a);
  int t = N / q.back();
  std::vector<int> ah = {t};
  std::vector<int> ph = {0, t * p.back()};
  std::vector<int> qh = {0, t * q.back()};

  for (int i = q.size() - 1; i; --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

# Find [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

Given positive integers A,B,N≤2×109A,B,N \le 2\times 10^9, find x,y≥0x,y\ge 0 such that Ax+By≤NAx+By\le N and Ax+ByAx+By is as large as possible.

Solution

This problem has an O(N)O(\sqrt N) solution: assume without loss of generality that A≥BA\ge B. Since A(B+x)+By=Ax+B(A+y)A(B+x)+By=Ax+B(A+y), it is enough to search over x≤min⁡{N/A,B}x\le\min\{N/A, B\}. This is sufficient to pass the problem. However, using continued fractions reduces the time complexity to O(log⁡N)O(\log N).

For convenience, first change the sign of xx by the substitution x↦⌊N/A⌋−xx\mapsto\left\lfloor N/A\right\rfloor-x. Let C=N mod AC=N\bmod A and M=⌊N/A⌋M=\left\lfloor N/A\right\rfloor. The original problem becomes finding the optimal (x,y)(x,y) under 0≤x≤M0\le x\le M and By−Ax≤CBy-Ax\le C, maximizing By−AxBy-Ax. For each fixed xx, the optimal value of yy is ⌊Ax+CB⌋\left\lfloor\dfrac{Ax+C}{B}\right\rfloor.

Next, we explain why this problem has a solution similar to that of the previous example. Unlike the previous example, which uses lower intermediate convergents to deviate from a line, this problem needs upper intermediate convergents to approach a line. Specifically, C−(By−Ax)C-(By-Ax) is proportional to the distance between (x,y)(x,y) and the line By−Ax=CBy-Ax=C. Maximizing By−AxBy-Ax is equivalent to minimizing this distance. The goal of the algorithm is to find the feasible lattice point below the line By−Ax=CBy-Ax=C that is closest to it. The idea is to start from the leftmost point and search along the upper convex hull of these lattice points, progressively reducing the distance to the line until the optimum is found.

In the (x,y)(x,y) coordinate system, the algorithm starts at (0,⌊C/B⌋)(0,\lfloor C/B\rfloor) and recursively finds and adds the optimal increment (Δx,Δy)(\Delta x,\Delta y), ensuring that the new point is closer to the line By−Ax=CBy-Ax=C than the previous point, without crossing to the other side of the line or making its x-coordinate exceed MM. If the point already obtained is (x,y)(x,y), then the increment (Δx,Δy)(\Delta x,\Delta y) must satisfy

0 $$ Following the idea of searching along a lower convex hull, we only need to find the point with the smallest $\Delta x$ among the points satisfying these conditions. Rewrite the first inequality as

\Delta y \le \dfrac{A}{B}\Delta x+\dfrac{C-(By-Ax)}{B}.

According to the [geometric interpretation](#几何解释) above, as long as the constant term on the right is less than $1$, the feasible lattice point $(\Delta x,\Delta y)$ with the smallest x-coordinate must correspond to an upper intermediate convergent. This is because, among all fractions with denominator no larger than its denominator, it is the one that best approaches a real number from above, which can only be an upper intermediate convergent. Each time an increment is added, the upper bound on $\Delta y$ becomes tighter, so intermediate convergents with larger denominators must be examined. Following the idea of the previous example, examine all upper intermediate convergents in increasing order of denominator. If an upper intermediate convergent has neither coordinate out of bounds, add it and update the corresponding upper bound. Once all feasible upper intermediate convergents have been added, the result is the optimum. Compared with the previous problem, this one must ensure that both coordinates remain within bounds, which requires extra care. Using an argument similar to that for the previous example, but replacing the previous $\Delta x$ with $B\Delta y-A\Delta x$, we can show that the complexity of this algorithm is $O(\log\min\{A,B\})$. **C++** ```py // Find (x, y) such that y = (A*x+B)/C, // such that Cy - Ax is max and 0 <= x <= N. auto closest(int A, int B, int C, int N) { // y <= (A*x + B)/C <=> diff(x, y) <= B auto diff = [&](int x, int y) -> int { return C * y - A * x; }; std::vector<int> p, q; std::tie(p, q) = convergents(fraction(A, C)); int qh = 0, ph = B / C; for (int i = 2; i < q.size() - 1; ++i) { if (i % 2 == 0) { while (diff(qh + q[i + 1], ph + p[i + 1]) <= B) { int t = 1 + (diff(qh + q[i - 1], ph + p[i - 1]) - B - 1) / (-diff(q[i], p[i])); int dp = p[i - 1] + t * p[i]; int dq = q[i - 1] + t * q[i]; int k = (N - qh) / dq; if (k == 0) { return std::make_pair(qh, ph); } if (diff(dq, dp) != 0) { k = std::min(k, (B - diff(qh, ph)) / diff(dq, dp)); } qh += k * dq; ph += k * dp; } } } return std::make_pair(qh, ph); } auto solve(int A, int B, int N) { int x, y; std::tie(x, y) = closest(A, N % A, B, N / A); return std::make_pair(N / A - x, y); } ``` **Python** ```py # Find (x, y) such that y = (A*x+B) // C, # such that 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 p, q = convergents(fraction(A, C)) qh, ph = 0, B // C for i in range(2, len(q) - 1): if i % 2 == 0: while diff(qh + q[i + 1], ph + p[i + 1]) <= B: t = 1 + (diff(qh + q[i - 1], ph + p[i - 1]) - B - 1) // ( -diff(q[i], p[i]) ) dp = p[i - 1] + t * p[i] dq = q[i - 1] + t * q[i] k = (N - qh) // dq if k == 0: return qh, ph if diff(dq, dp) != 0: k = min(k, (B - diff(qh, ph)) // diff(dq, dp)) qh, ph = qh + k * dq, ph + k * dp return qh, ph def solve(A, B, N): x, y = closest(A, N % A, B, N // A) return N // A - x, y ```
June Challenge 2017 - Euler Sum

Find the value of ∑x=1N⌊ex⌋\sum\limits_{x=1}^N \lfloor \mathrm{e}x \rfloor, where e\mathrm{e} is the base of the natural logarithm.

Hint: 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,\cdots,1,2n,1, \cdots].9

Solution

This sum equals the number of lattice points in the set {(x,y):1≤x≤N,1≤y≤ex}\{(x,y):1\le x\le N,1\le y\le\mathrm{e}x\}. After constructing the convex hull of the lattice points below the line y=exy=\mathrm{e}x, the Pick theorem can be used to count the lattice points. The time complexity is O(log⁡N)O(\log N).

The original problem requires N≤104000N \le 10^{4000}. The C++ code below is only illustrative and does not implement an arbitrary-precision arithmetic class.

C++

// Find sum of floor(k * x) for k in [1, N] and x = [a0; a1, a2, ...]
int sum_floor(std::vector<int> a, int N) {
  N++;
  std::vector<int> ah, ph, qh;
  std::tie(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 {
    int b = y1 + y2 + a + dx;
    int A = (y1 + y2) * dx;
    return (A + b) / 2 - y2;  // = (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

# Find sum of 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) but with
    # the number of points on the vertical right line excluded.
    def picks(y1, y2, dx, a):
        b = y1 + y2 + a + dx
        A = (y1 + y2) * dx
        return (A + b) // 2 - y2  # = (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 positive integers p,q,np,q,n, find the value of ∑i=1n[pi mod q]\sum\limits_{i=1}^n [pi \bmod q].

Solution

Since the sum can be rewritten as

∑i=1n[pi mod q]=∑i=1n(pi−q⌊piq⌋)=pn(n+1)2−q∑i=1n⌊pqi⌋,\sum_{i=1}^n [pi \bmod q] =\sum_{i=1}^n\left(pi - q\left\lfloor\dfrac{pi}{q}\right\rfloor\right) = \dfrac{pn(n+1)}{2} - q\sum_{i=1}^n\left\lfloor\dfrac{p}{q}i\right\rfloor,

this problem can be reduced to the previous one by replacing e\mathrm{e} with pq\dfrac{p}{q}. The time complexity of a single query is O(log⁡min⁡{p,q})O(\log\min\{p,q\}).

C++

int solve(int p, int q, int n) {
  return p * n * (n + 1) / 2 - q * sum_floor(fraction(p, q), n);
}

Python

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 positive integers N,M,A,BN,M,A,B, find the value of ∑i=0N−1⌊A⋅i+BM⌋\displaystyle\sum_{i=0}^{N-1} \left\lfloor \frac{A \cdot i + B}{M} \right\rfloor.

Solution

This is the most complicated problem so far. It can be solved using the Euclidean-like algorithm. Here we give an algorithm based on continued fractions, with time complexity O(log⁡min⁡{A,B})O(\log\min\{A,B\}).

We can construct the convex hull of all lattice points below y=Ax+BMy=\dfrac{Ax+B}{M} with 0≤x<N0\le x< N, and use Pick's theorem to count the lattice points. The case B=0B=0 was solved earlier. For the general case, we can proceed in two steps. First, progressively approach the line by adding upper intermediate convergents (the second example), until the closest point on the line is found; then progressively move away from the line by adding lower intermediate convergents (the first example).

C++

// Find convex hull of lattice (x, y) such that C*y <= A*x+B.
auto hull(int A, int B, int C, int N) {
  auto diff = [&](int x, int y) -> int { return C * y - A * x; };
  auto a = fraction(A, C);
  std::vector<int> p, q;
  std::tie(p, q) = convergents(a);
  std::vector<int> ah(0), ph(1, B / C), qh(1, 0);
  auto insert = [&](int dq, int dp) -> void {
    int k = (N - qh.back()) / dq;
    if (diff(dq, dp) > 0) {
      k = std::min((int)k, (B - diff(qh.back(), ph.back())) / diff(dq, dp));
    }
    ah.emplace_back(k);
    qh.emplace_back(qh.back() + k * dq);
    ph.emplace_back(ph.back() + k * dp);
  };
  for (int i = 1; i < q.size() - 1; ++i) {
    if (i % 2 == 0) {
      while (diff(qh.back() + q[i + 1], ph.back() + p[i + 1]) <= B) {
        int t = (B - diff(qh.back() + q[i + 1], ph.back() + p[i + 1])) /
                (-diff(q[i], p[i]));
        int dp = p[i + 1] - t * p[i];
        int dq = q[i + 1] - t * q[i];
        if (dq < 0 || qh.back() + dq > N) break;
        insert(dq, dp);
      }
    }
  }
  insert(q.back(), p.back());
  for (int i = q.size() - 1; i; --i) {
    if (i % 2 == 1) {
      while (qh.back() + q[i - 1] <= N) {
        int 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];
        insert(dq, dp);
      }
    }
  }
  return std::make_tuple(ah, ph, qh);
}

// Sum of floor (Ax+B)/M from 0 to N-1.
auto solve(int N, int M, int A, int B) {
  std::vector<int> ah, ph, qh;
  std::tie(ah, ph, qh) = hull(A, B, M, 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) but with
  // the number of points on the vertical right line excluded.
  auto picks = [&](int y1, int y2, int dx, int a) -> int {
    int b = y1 + y2 + a + dx;
    int A = (y1 + y2) * dx;
    return (A + b) / 2 - y2;  // = (A - b + 2) // 2 + b - (y2 + 1)
  };
  int ans = 0;
  for (int 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

# Find convex 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])) // (
                    -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


def solve(N, M, A, B):
    ah, ph, qh = hull(A, B, M, 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) but with
    # the number of points on the vertical right line excluded.
    def picks(y1, y2, dx, a):
        b = y1 + y2 + a + dx
        A = (y1 + y2) * dx
        return (A + b) // 2 - y2  # = (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
OKC 2 - From Modular to Rational

There is an unknown rational number pq\dfrac{p}{q} with 1≤p,q≤1091\le p, q\le 10^9. For a prime m∈[109,1012]m\in[10^9,10^{12}], you may query the value of pq−1pq^{-1} after reducing it modulo that prime. Determine the values of pp and qq in no more than ten queries.

This problem is equivalent to finding, in [1,N][1,N], the value that minimizes Ax mod MAx\bmod M, namely xx.

Solution

According to the Chinese remainder theorem, querying the results modulo multiple primes is equivalent to querying the result modulo the product of those primes. Therefore, this problem can be regarded as querying the result of taking the fraction modulo a sufficiently large modulus mm, with the numerator and denominator of the fraction to be determined.

For a given modulus mm, it need not be the case that the pairs satisfying qr≡p(modm)qr\equiv p\pmod m—namely (p,q)(p,q)—are unique. Suppose that both (p1,q1)(p_1,q_1) and (p2,q2)(p_2,q_2) can make this equation hold. Then it necessarily follows that (p1q2−p2q1)r≡0(modm)(p_1q_2-p_2q_1)r\equiv 0\pmod m. From the construction of rr, we know that rr is coprime to mm, so p1q2−p2q1≡0(modm)p_1q_2-p_2q_1\equiv 0\pmod m, or equivalently, m∣(p1q2−p2q1)m\mid(p_1q_2-p_2q_1). If p1q2−p2q1p_1q_2-p_2q_1 is nonzero, then its absolute value is at least mm. The problem constrains p,q∈[1,109]p,q\in[1,10^9], which means that this difference should not exceed 101810^{18}. Thus, taking m>1018m>10^{18} guarantees that the resulting (p,q)(p,q) is unique.

The problem now reduces to this: given a modulus mm and a remainder rr, find, for a bound nn, positive integer pairs (p,q)(p,q) with both values no greater than that bound such that qr≡p(modm)qr\equiv p\pmod m. Once it is known that such a solution is unique, it is enough to find the q∈[1,n]q\in[1,n] such that the minimum of qr mod mqr\bmod m is attained at qq, because in that case there is exactly one qq whose remainder does not exceed nn. This is precisely the equivalent formulation mentioned above.

In the plane with coordinates (q,k)(q,k), this amounts to finding, for q∈[1,n]q\in[1,n], the lattice point below and closest to the line qr−km=0qr-km=0, because the remainder qr mod mqr\bmod m is directly proportional to the distance between the lattice point and the line. Combining this with the geometric interpretation given earlier, we see that this lattice point must correspond to one of the lower semiconvergents of the rational fraction rm\dfrac{r}{m}. The algorithm has complexity O(log⁡min⁡{r,m})O(\log\min\{r,m\}).

C++

// Find Q that minimizes Q*r mod m for 1 <= k <= n < m.
int mod_min(int r, int n, int m) {
  auto a = fraction(r, m);
  std::vector<int> p, q;
  std::tie(p, q) = convergents(a);
  for (int i = 2; i < q.size(); ++i) {
    if (i % 2 == 1 && (i + 1 == q.size() || q[i + 1] > n)) {
      int t = (n - q[i - 1]) / q[i];
      return q[i - 1] + t * q[i];
    }
  }
  return 0;
}

Python

# 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]
    return 0

Exercises

References and Further Reading

The main content of this page is translated from the blog post Continued fractions under the CC-BY-SA 4.0 license, with modifications.

Footnotes

  1. The natural number 11 has only the non-standard representation 1=[1]=[0,1]1=[1]=[0,1]. ↩

  2. The translated term comes from Section 6.7 of Concrete Mathematics, translated by Zhang Mingyao and Zhang Fan. ↩

  3. At this point, one cannot assume that the reduced fraction pq\dfrac{p}{q} must be a convergent, although Legendre's theorem shows that pq\dfrac{p}{q} can indeed only be a convergent. In the case of convergents, this can be proved by starting from the error with which a convergent approximates the real number. ↩

  4. Different references may handle differently whether the endpoints are included in the range of tt here. ↩

  5. When t=0t=0, it should be understood as a formal continued fraction, equivalent to truncating the continued fraction at its penultimate term. ↩

  6. This is not a technical term. It may have been translated from the Russian literature ЦЕПНЫЕ ДРОБИ, in the section Алгоритм «вытягивания носов». ↩

  7. These properties show that the group of all fractional linear transformations is isomorphic to the projective linear group PGL2(R)PGL_2(\mathbf R). ↩

  8. A proof can be found in the references of the Wikipedia page. ↩

  9. A proof of the continued fraction expansion of the base of the natural logarithm, e\mathrm{e}, can be found here. ↩

This content comes from OI Wiki: Continued fraction. See the original for authors and revision history. AIOJ has adapted the formatting, in-site links, and resource paths.

Content is shared under CC BY-SA 4.0 and SATA license; additional terms are governed by the original notice. Thanks to the OI Wiki authors and contributors; per the SATA terms, please visit the OI Wiki repository and star it to show your support.