Skip to Content
MathematicsMathematics
  • Feature Paper
  • Article
  • Open Access

22 September 2026

27 Pages

An Infinite Precision Implementation of Regular Periodic Infinite Continued Fractions

INESC-ID, Instituto Superior Técnico, Universidade de Lisboa, Avenida Rovisco Pais 1, 1049-001 Lisboa, Portugal

Abstract

We give a detailed description of the process that is used to obtain the regular periodic continued fraction that represents D , where D is a non-square positive integer. We give a new combinatorial proof of Lagrange’s theorem, showing that this process eventually enters a loop. We provide an infinite precision implementation of this process with the GMP library. We consider two algorithms for identifying the initial states, before the process reaches a state in the loop, and both require storing a constant amount of integers. Our experimental results show that the algorithm based on Galois’s criteria is faster than using Floyd’s algorithm, especially when the number of initial states is small. We also give an implementation of the inverse process of determining a degree-two polynomial that yields a particular continued fraction.

1. Introduction

We discuss a process for obtaining continued fractions that represent square roots, i.e., numbers of the form D where D > 1 is a positive non-square integer. For example, 61 can be represented by an infinite periodic regular continued fraction as 7 + 1 / ( 1 + 1 / ( 4 + 1 / ( 3 + 1 / ( 1 + 1 / ( 2 + 1 / ( 2 + 1 / ( 1 + 1 / ( 3 + 1 / ( 4 + 1 / ( 1 + 1 / ( 14 + … ) ) ) ) ) ) ) ) ) ) ) , where the ellipsis portion can be replaced by the same expression without the initial 7. We use the following notation to represent this continued fraction is [ 7 ; ( 1 , 4 , 3 , 1 , 2 , 2 , 1 , 3 , 4 , 1 , 14 ) ] . In this notation the periodic part of the fraction is shown inside parenthesis. The coefficients are separated by commas, except for the initial integer part, which uses a semicolon. For the fraction to be classified as regular, all the values should be positive integers, but the notation itself can be used with any number, so for example, [ 0 ; 0.5 ] = 2 . The numerical representation of 61 is around 7.8102497 . Where the initial value of 7 is the integer part of 61 . To obtain the next value in the expansion, we need to find the value y such that 61 = 7 + 1 / y . Using some algebra this number simplifies to y = ( 7 + 61 ) / 12 . Now the integer part of this number is 1. This value is simpler to calculate as ⌊ ( 7 + 7 ) / 12 ⌋ . Hence we can again find the next number as ( − 1 + ( 7 + 61 ) / 12 ) − 1 . This simplifies to ( 5 + 61 ) / 3 . Again, we can repeat this process by observing that the integer part of this number is 4 = 12 / 3 and then obtain ( 7 + 61 ) / 4 . So far, this sequence of numbers has no indication of repeating but let us consider the full sequence:
x = 0 + 61 1 7 + 61 12 5 + 61 3 7 + 61 4 5 + 61 9 4 + 61 5 6 + 61 5 4 + 61 9 5 + 61 4 7 + 61 3 5 + 61 12 7 + 61 1 ⌊ x ⌋ = 7 1 4 3 1 2 2 1 3 4 1 14
Now consider the last element in the sequence 7 + 61 . Notice that its integer part is 14, by applying the usual transformation we obtain ( 7 + 61 ) / 12 . This number occurred as the second number in the sequence, thus this process will now repeat indefinitely.
In this paper we focus in achieving the following goals:
  • Provide a detailed description of the process of computing the regular periodic infinite continued fraction of non-square integer D. We study this process both as a sequence of surds and as a sequence of degree-two polynomial roots, see Lemma 1. Except for Theorem 3, all other results apply to a general sequence of degree-two polynomials with real roots and integer coefficients that do not necessarily represent a square root of D.
  • We give a new combinatorial proof that this sequence of numbers will eventually repeat, see Theorem 1. We also describe how to invert this process by obtaining a polynomial that produces a desired continued fraction, Theorem 2.
  • We then describe how to implement these processes with the GNU MP library and how to use Floyd’s algorithm or Galois’s criteria to determine the size of the initial sequence and the size of the looping sequence in minimal space, Section 3.2. We experimentally validate the performance of our implementation, Section 4.

2. General Form

Let us consider the general procedure for generating these types of sequences. A general term in the sequence is represented by the variable x. Note that we always have x > 0 . We are only interested in the continued fraction representation of positive numbers of the form D . We can observe that, in this example, the value D is constant throughout the process. This is true in general. The general form for x is then as follows:
x = − B + D A
In this expression, A and B are integers. In the simple case when B = 0 and A = 1 , the surd simplifies to the square root of D. Also note that this general form can be used to represent the square root of a rational number, i.e., x = p / q = p q / q . Hence we could use A = q , B = 0 , and D = p q . An interesting property of this expression is that the coefficient associated with D is always 1. It is not immediately clear why this should be so. We will explain why this property holds in a moment. Before that, let us summarized the information that is necessary to identify a state of the sequence. It consists of the integers A and B. The value of D is stored globally and not in the state information.
To explain why D remains invariant and that the coefficient of D is always 1, we need to consider an alternate form of representing x. For this goal we use a quadratic equation ( A x + B ) 2 − D = 0 . Now x is a zero of this equation. The  polynomial representation is useful in determining the transformation process. To start, we expand the polynomial into A 2 x 2 + 2 A B x + B 2 − D . This representation has the desirable property that all the coefficients are integers. Moreover, we divide by A ≠ 0 to have simple coefficients for the x 2 and x terms. Thus we will consider the following polynomial:
q ( x ) = ( A x + B ) 2 − D A = A x 2 + 2 B x + B 2 − D A
Again, x is a zero in this polynomial. Note that the surd in Equation (1) corresponds to the usual quadratic formula. In general, there are two solutions to a quadratic equation, which is normally represented by a ± sign. When A > 0 , the plus represents the largest solution and the minus the smallest one. We will always use a plus sign of for D . Hence it is possible to represent the smallest solution by changing the sign of A and B. Hence the other zero of the quadratic equation is B + D − A . Incorporating these considerations into the expansion process means that, when A is positive, x is the largest zero of the quadratic equation q ( x ) = 0 and, when A is negative, x is instead the smallest zero.
There is another question with the representation of q ( x ) . Is ( B 2 − D ) / A an integer? When this term is an integer, we say that Equation (1) is a canonical representation of the surd. In this case, it is possible to choose a degree-two polynomial q ( x ) = A x 2 + 2 B x + C with integer coefficients. Moreover, by rewriting the formula for C, we obtain that D = B 2 − A C . Therefore, the value of D is similar to the usual discriminate expression of the quadratic formula. In fact, it is the usual value divided by 4, i.e.,  D = ( ( 2 B ) 2 − 4 A C ) / 4 .
Even though not all representations are canonical, it is always possible to obtain a canonical form. To illustrate this point we consider the surd ( − 1 + 5 ) / 3 . Let us assume that a non-canonical has the following form:
x = − B * + D * A *
In this example, we have that B * = 1 , D * = 5 , and A * = 3 . Now the expression ( B * 2 − D * ) / A * evaluates to − 4 / 3 , which is not an integer. Note that this problem does not occur when the surd is a pure square root, i.e., when B * = 0 and A * = 1 . In such a case ( B * 2 − D * ) / A * = − D * , which is an integer. Hence transforming a non-canonical representation into a canonical representation is only necessary when computing the continued fraction representation of a generalized surd. In the remainder of this section we explain this process. Hence the reader who is only interested in the continued fraction representation of a square root can safely skip to Section 3.
We thus want to modify the surd representation, without  altering the actual value of x. Hence we multiply both the numerator and denominator by | A * | . We thus obtain the following:
x = − B * | A * | + D * A * 2 A * | A * | = − B + D A
Hence, to obtain a canonical representation from a non-canonical one, we set A = A * | A * | , B = B * | A * | , and D = D * A * 2 . In our example, the resulting representation is ( − 3 + 45 ) / 9 , which represents the same value of x as before. In this representation B = 3 , D = 45 , and A = 9 . Hence the expression ( B 2 − D ) / A evaluates to − 36 / 9 = − 4 . This is indeed an integer, as 9 is a factor of − 36 .
It is straight forward to check that this procedure works in general as A * | A * | will always be a factor of B * 2 A * 2 − D * A * 2 . Therefore, we can assume without loss of generality that the original representation was canonical and therefore C = ( B 2 − D ) / A = sgn ( A * ) ( B * 2 − D * ) represents an integer. Note that, in this last expression, sgn ( A * ) represents the sign of the value A * . Again, for the above example, we obtain C = + 1 × ( 1 − 5 ) = − 4 .
Also note that a canonical representation is not necessarily unique. We can further multiply both the numerator and denominator by some integer. For example, if we multiply the last configuration by 2, we obtain ( − 6 + 180 ) / 18 , which represents the same value of x as the previous forms. In general, we prefer the simpler canonical form, i.e., when the greatest common divisor of A, B, and C is 1. Still, this is not strictly necessary because the process we describe is still correct when A, B, and C have a non-trivial common factor. However, a GCD of 1 has the advantage of reducing the computational complexity of the underlying integer operations, addition, subtraction, multiplication, and division. For  completeness, note that, for ( − 3 + 45 ) / 9 , we have A = 9 , B = − 3 , and C = − 4 , with a GCD of 1, and for ( − 6 + 180 ) / 18 , we have A = 18 , B = − 6 , and C = − 8 with a GCD of 2.
We will soon show that the value of D is invariant on the steps taken to compute the continued fraction, Section 3.1. This is not the case for the transformation from the non-canonical representation to the canonical one. In particular, in the example we considered, the initial value of D * was 5, but the value of D in the canonical representation was 45 = 9 × 5 , i.e., the value was multiplied by A 2 = 9 . This is the case in general because the canonization process uses D = D * A * 2 .

3. Sequence Properties

In this section we describe the general computation procedure, along with several important properties. Section 3.1 contains a complete overview, but we delay proofs and details to Section 3.3.

3.1. Complete Overview

Now let us focus on a step of the process. We first determine the integer part of x as p = ⌊ x ⌋ . We then compute the next number y in the sequence using the following process:
y = 1 / ( x − p ) = − B + D A − p − 1 = − A ( A p + B ) − D = − A ( ( A p + B ) + D ) ( A p + B ) 2 − D = ( A p + B ) + D − q ( p )
Hence we can write y in the same form as x, i.e., y = ( − B ′ + D ) / A ′ . Given the above derivation, we obtain the following update formulas:
A ′ = − q ( p )
− B ′ = A p + B
This derivation established that the value of D is preserved, and so is the sign and coefficient of D . Moreover, it also establishes that A ′ and B ′ are integers. From Equation (4) it is simple to conclude that B ′ is an integer because A, B, and p are also integers. Concluding that A ′ is an integer follows from Equation (3) and the fact that C is an integer, discussed in Section 2. Hence, to preserve this property, by induction, for all the elements in the sequence, we need an update formula for C ′ . This can be obtained by studying the update process with the polynomial q ( x ) . We deduce the same update formulas if we transform the polynomial q ( x ) into the polynomial q ′ ( y ) = A ′ y 2 + B ′ y + C ′ by applying the substitution x = p + 1 / y . We then multiply by − y 2 and collect similar terms:
q ′ ( y ) = − ( A p 2 + 2 B p + C ) y 2 − 2 ( A p + B ) y − A = 0
This yields the same update formulas as before and furthermore gives us the update C ′ = − A . Hence we conclude that C ′ must also be an integer, given that A is known to be an integer.
Note that we can multiply the whole equation by − 1 . In this case the update formulas would become A ′ = q ( p ) , B ′ = A p + B and C ′ = A . However, if we used these formulas, we would need also to keep track of the sign of D . To avoid extra book-keeping we instead use the updates given by Equations (3) and (4).
In the surd representation it is clear that the value of D does not change in this process, i.e.,  D ′ = D . However, in the polynomial representation, this fact is not immediate. It can be observed by evaluating D ′ = B ′ 2 − A ′ C ′ as follows:
D ′ = ( A p + B ) 2 − ( A p 2 + 2 B p + C ) A = B 2 − A C = D
On the other hand, the polynomial update formulas are necessary to prove that, if the original coefficients are integers, the updated values are also integers, as explained. We can thus summarize the whole process in the following lemma:
Lemma 1.
Given a non-square positive integer D, it is possible to obtain its regular continued fraction representation [ p 1 : p 2 , … ] with values p i > 0 obtained as the integer part of a sequence of surds defined as x 1 = D and x i = p i + 1 / x i + 1 with canonical representations as x i = − B i + D A i > 1 and the following properties:
1. 
Values A i , B i , and C i = ( B i 2 − D ) / A i are always integers.
2. 
x i is a solution of the quadratic equation q i ( x ) = A i x 2 + 2 B i x + C i = 0 . If  A i > 0 , then x i is the largest solution; otherwise, x i is the smallest solution.
3. 
These values are updated as A i + 1 = − q i ( p i ) , − B i + 1 = A i p i + B i , and C i + 1 = − A i .
We illustrate the values in this lemma, using the example with D = 61 .
i 1 2 3 4 5 6 7 8 9 10 11 12 13 = 2 … 61 ≥ B i = 0 − 7 − 5 − 7 − 5 − 4 − 6 − 4 − 5 − 7 − 5 − 7 − 7   A i = 1 12 3 4 9 5 5 9 4 3 12 1 12   C i = − 61 − 1 − 12 − 3 − 4 − 9 − 5 − 5 − 9 − 4 − 3 − 12 − 1   p i = 7 1 4 3 1 2 2 1 3 4 1 14 1  
This table contains the same information presented in the surd sequence, but arranged according to the notation of Lemma 1. Note that in this sequence the A i values are always positive and the B i values are always smaller than 61 . The relation between these two observations is given by the following lemma.
Lemma 2.
During the execution of this process if A i > 0 then B i ≤ D ; otherwise, if A i < 0 , then − D ≤ B i .
The case where A i > 0 follows from Equation (1). For the other case, see the proof in Section 3.3. In essence, Lemma 2 restricts the range of values that B i can assume. However, this range of values is still infinite. Thus, to establish a restriction that forces the sequence of surds to repeat, we will show that the values of B i are actually strongly attracted to the interval [ − D , + D ] . This forces the sequence of B i values to assume values inside this interval an infinite number of times. Therefore, the B i values will eventually repeat because the values are necessarily integers and there is only a finite number of integers inside this interval. This is the core of our proof.
Lemma 3.
If  | B i | > D , then | B i | > | B i + 1 | , for any index i ≥ 1 .
This is shown by using the update formula and proving that B i 2 > B i + 1 2 , see Section 3.3. An interesting consequence of this lemma when combined with the formula C i = ( B i 2 − D ) / A i from Lemma 1 is that, if for some value of i we have C i A i > 0 , then C i A i > C i + 1 A i + 1 . The lemma’s hypothesis may seem unlikely; in fact, it never occurs in the example table for D = 61 , near Lemma 1. However, it may indeed occur in a general sequence of surds. Another example table for D = 61 is shown near Theorem 2, where the | B i | values form the sequence 245,725 > 11,341 > 336 > D = 61 ≈ 7.8102497 .
We can now complete our argument to show that the sequence of surds will eventually repeat.
Theorem 1
(Lagrange). For any non-square positive integer D, the value D can be represented by an infinite periodic regular continued fraction. More precisely, for the sequence of quadratic polynomials defined in Lemma 1, there exists an index m ≥ 0 and a period of size n such that, for any index i > m , we have q i ( x ) = q i + n ( x ) .
Our argument uses the pigeon hole principle by noticing that the number of integers in the interval [ − D , D ] is finite and that Lemma 3 forces B i to return to this interval an infinite number of times. Likewise, we show that the corresponding A i is also forced to be chosen from a finite set. For the detailed proof, see Section 3.3.
There are several natural questions that can arise from these results. How large are the cycles in relation to D? What are the properties of A i , B i when they are inside a cycle versus when they are in the initial phase? We will answer these questions shortly, as they provide further insight into the cycling process.
Our proof of Theorem 1 implies that, for both A i and B i , values inside the cycle are limited to integers from a set of size O ( D ) . Therefore, the maximum cycle will be O ( D ) . However, sharper bounds of O ( D log D )  [1,2] are known.
By observing our current example we immediately notice that, for the values inside the cycle, the values of A i are always positive and therefore the values of C i are always negative. Moreover, inside the cycle we always observe | B i | ≤ D . These observations turn out to be true in general.
To establish these observations we also implemented the converse of the previous theorem, i.e., the process of determining D for a given cycle of n integers p m + 1 , … , p m + n . In fact, we implemented a function that, given a sequence of m numbers p 1 , … , p m and a cycle, outputs the values A 1 , B 1 , and D such that x 1 = [ p 1 ; p 2 , … , p m , ( p m + 1 , … , p m + n ) ] is a zero of the corresponding polynomial q 1 ( x ) .
This is implemented in a two-step process. In the first step we determine A m + 1 , B m + 1 and D for the corresponding cycle. In the second step we prepend the information related to the initial part of the fraction. To solve the first step we essentially need to write the equation x m + 1 = [ p m + 1 ; p m + 2 , … , p m + n , x m + n + 1 ] and simultaneously have x m + n + 1 = x m + 1 . We can obtain a more explicit form for the right side of the equation by evaluating the convergents of the continued fraction. The i-th convergent is h i / k i , where h i and k i are positive integers. To maintain the indexes consistent throughout the presentation, we start the convergent sequence for i = m + 1 . Hence the integer sequence h i is defined, for  i > m , recursively, as follows:
h i = p i h i − 1 + h i − 2
Two base numbers need to defined, h m = 1 and h m − 1 = 0 . The integers k i are defined with a similar recurrence to Equation (6). However, the base numbers are instead k m = 0 and k m − 1 = 1 . Hence we can now write the desired equation for x m + 1 .
x m + 1 = x m + n + 1 h m + n + h m + n − 1 x m + n + 1 k m + n + k m + n − 1
We can now simplify both x m + 1 and x m + n + 1 to x = x m + 1 = x m + n + 1 and rearrange terms and multiply by two to obtain the following equation:
2 k m + n x 2 + 2 ( k m + n − 1 − h m + n ) x − 2 h m + n − 1 = 0
We have thus obtained the form of q m + 1 ( x ) , where A m + 1 = 2 k m + n , B m + 1 = k m + n − 1 − h m + n , and C m + 1 = − 2 h m + n − 1 . Moreover, the value of D can now be determined as D = ( k m + n − 1 − h m + n ) 2 + 4 k m + n h m + n − 1 . Note that the h i and k i values are always non-negative integers, for any index i. The continued fraction representation of the root x that satisfies this equation is a purely periodic continued fraction.
In Lemma 4 we highlight some properties of the coefficients A i , B i , and C i inside the cycle. Note that it is possible to flip the signs of all the coefficient and still obtain the same roots. However, in our approach, we use a positive value of A m + 1 when considering the largest root of q m + 1 ( x ) . Hence we need to verify that we are interested in the largest root of q m + 1 ( x ) . For this, we observe that the formula for D implies that B 2 ≤ D and therefore that | B | ≤ D , i.e., the hypothesis of Lemma 3 is false. This also implies that − B − D is necessarily a negative number, even when B is negative. Therefore, the smallest root of q m + 1 ( x ) is a negative number and not the desired root. We can now establish some properties for the coefficients inside the cycle.
Lemma 4.
Let m be the index described in Theorem 1. For any i > m , we have that A i > 0 , C i < 0 , | B i | < D , and A i + C i > 2 B i .
This is a consequence of the formulation in Equation (8), see Section 3.3 for the proof.
It turns out that whenever the conditions A i > 0 and C i < 0 occur they are preserved by the update process and moreover also imply the other properties. Note that the next result does not require the restriction that i is inside the cycle.
Lemma 5.
For any quadratic polynomial q i ( x ) defined in Lemma 1, if  A i > 0 and C i < 0 , then A i + 1 > 0 , C i + 1 < 0 , − D < B i + 1 < 0 , and A i + 1 + C i + 1 > 2 B i + 1 .
A schematic representation of the corresponding parabola is given in Figure 1, which illustrates the result. The formal proof is given in Section 3.3.
Figure 1. Plot of q i ( x ) in the conditions of Lemma 5.
This lemma provides insights into the proof of Theorem 1. Essentially, the lemma locks the sign configuration of the coefficients. Moreover, in this configuration, we have a solution for the Diophantine equation B 2 − A C = D , where − A C is a positive number. For a fixed value of D, there is a finite amount of such solutions. In fact, the size of these cycles is known to be bounded by O ( D log D )  [1,2], although bounds based on the number of solutions to this Diophantine equation are a bit larger [3,4].
Before considering the second process, we highlight the mirror property, which will be relevant for Galois’s theorem. The previous process focused on determining the coefficients of the equation x m + 1 = [ p m + 1 ; p m + 2 , … , p m + n , x m + 1 ] . Let us simplify x m + 1 to x and write the equation more explicitly so that we can manipulate it. In essence, our goal is to transfer the p values from the right side of the equation to the left side. The following derivation gives an illustration of the process
x = − ( − x ) = p m + 1 + 1 / ( p m + 2 + 1 / ( p m + 3 + 1 / ( … p m + n + 1 / x … ) ) ) − 1 / ( p m + 1 − x ) = p m + 2 + 1 / ( p m + 3 + 1 / ( … p m + n + 1 / x … ) ) − 1 / ( p m + 3 + 1 / ( p m + 2 + 1 / ( p m + 1 − x ) ) ) = … p m + n + 1 / x … … − 1 / ( p m + n + … 1 / ( p m + 3 + 1 / ( p m + 2 + 1 / ( p m + 1 − x ) ) ) … ) = 1 / x 1 / ( p m + n + … 1 / ( p m + 3 + 1 / ( p m + 2 + 1 / ( p m + 1 − x ) ) ) … ) = − 1 / x 1 / ( p m + n + … 1 / ( p m + 3 + 1 / ( p m + 2 + 1 / ( p m + 1 − x ) ) ) … ) ¯ = − 1 / x ¯ l 1 / ( p m + n + … 1 / ( p m + 3 + 1 / ( p m + 2 + 1 / ( p m + 1 − x ¯ ) ) ) … ) = − 1 / x ¯ 1 / ( p m + n + … 1 / ( p m + 3 + 1 / ( p m + 2 + 1 / ( p m + 1 + 1 / z ) ) ) … ) = z
Note that, in the last equation, we substituted − 1 / x ¯ by z and obtained a new equation. Note that, before the substitution, we apply the algebraic conjugate to both sides of the equation. This step is not strictly essential, but it makes the mapping from the roots of one equation to the roots of the other equation coincide with the variable substitution. In essence, the issue is that, if x > 0 , then − 1 / x < 0 and therefore its continued fraction expansion cannot be obtained by using only positive integers p i . Hence the expansion we obtain is actually the representation of − 1 / x ¯ > 0 . Alternatively, the same derivation can be illustrated with continued fraction notation:
x = − [ − x ] = [ p m + 1 ; p m + 2 , … , p m + n , x ] − [ 0 ; − 1 / x ] = [ p m + 1 ; p m + 2 , … , p m + n , x ] − [ p m + 1 ; − 1 / x ] = [ 0 ; p m + 2 , … , p m + n , x ] − [ 0 ; p m + 1 , − 1 / x ] = [ p m + 2 ; … , p m + n , x ] − [ p m + 2 ; p m + 1 , − 1 / x ] = [ 0 ; … , p m + n , x ] − [ 0 ; p m + 2 ; p m + 1 , − 1 / x ] = [ … , p m + n , x ] … − [ 0 ; … , p m + 2 ; p m + 1 , − 1 / x ] = [ p m + n ; x ] − [ p m + n ; … , p m + 2 ; p m + 1 , − 1 / x ] = [ 0 ; x ] = 1 / x p m + n ; … , p m + 2 ; p m + 1 , − 1 / x ]   = − 1 / x p m + n ; … , p m + 2 ; p m + 1 , − 1 / x ¯ ]   = − 1 / x ¯ p m + n ; … , p m + 2 ; p m + 1 , z ] = z
The solution of the new equation on z is now such that its continued fraction expansion is the mirror of the original one. Stated in another way, x = [ p m + 1 ; p m + 2 , … , p m + n , x ] and z = [ p m + n ; … , p m + 2 , p m + 1 , z ] . We can now consider this substitution from the point of view of the quadratic equation. In essence, we want to apply the substitution to the following equation:
A x 2 + 2 B x + C = 0
Using the substitution x = − 1 / z ¯ , we obtain the following:
A / z ¯ 2 − 2 B / z ¯ + C = 0 − C z ¯ 2 + 2 B z ¯ − A = 0 − C z ¯ 2 + 2 B z ¯ − A ¯ = 0 ¯ − C z 2 + 2 B z − A = 0
To obtain the second form, we multiply both sides by − z 2 . Note that we multiply by − z 2 , instead of z 2 , because we know that inside the cycle the value of C is negative and we want the coefficient of z 2 to be positive. Hence we conclude that, given a quadratic equation q ( x ) = 0 such that its solution is a purely periodic continued fraction, it is possible to obtain a quadratic equation whose solution is the mirror continued fraction by flipping the sign of A and C and swapping them with each other. As an example of this lemma, consider the surd ( 5 + 61 ) / 3 , which we know is part of the cycle for 61 . For this surd the corresponding equation is 9 x 2 − 5 × 2 x − 4 = 0 and the corresponding solution is [ ( 1 ; 2 , 2 , 1 , 3 , 4 , 1 , 14 , 1 , 4 , 3 ) ] . Hence the corresponding equation on z = − 1 / x is 4 z 2 − 5 × 2 z − 9 = 0 and the solution is the mirror z = [ ( 3 ; 4 , 1 , 14 , 1 , 4 , 3 , 1 , 2 , 2 , 1 ) ] . In our example there is another equation that is worth pointing out in the context of this lemma. For the surd ( 6 + 61 ) / 5 the corresponding equation is 5 x 2 − 6 × 2 x − 5 = 0 . Notice that in this equation A = − C . Therefore, the lemma implies that the corresponding solution should be a mirror of itself. Hence the continued fraction expansion should be a palindrome. Indeed, we have that the solution is x = [ ( 2 ; 1 , 3 , 4 , 1 , 14 , 1 , 4 , 3 , 1 , 2 ) ] .
Lemma 6.
If the largest solution of a quadratic equation q ( x ) = A x 2 + 2 B x + C = 0 , with integer coefficients, is a purely periodic continued fraction, then the largest solution of the quadratic equation − C z 2 + 2 B z − A = 0 is the purely periodic continued fraction that mirrors x.
Let us now move on to the second process, prepending the initial sequence. For this we proceed backwards. We will determine q m ( x ) from q m + 1 ( x ) . To use a notation similar to that of Equation (5), we write x for x m , y for x m + 1 , and A ′ , B ′ , and C ′ for the coefficients of q ′ ( y ) = q m + 1 ( y ) . Our goal is to now obtain the coefficients A, B, and C of q ( x ) = q m ( x ) . Hence we rewrite the equation x = p + 1 / y , where p = p m , to obtain y = 1 / ( x − p ) . We can now substitute this into q ′ ( y ) = 0 . After some algebra we obtain the following equation:
− C ′ x 2 + 2 ( C ′ p − B ′ ) x − ( A ′ − 2 B ′ p + C ′ p 2 ) = 0
This therefore implies the following update formulas:
A = − C ′
B = C ′ p − B ′
C = − p 2 q ′ ( − 1 / p )
These formulas are chosen to perfectly invert the formulas of the forward direction. This can be seen by writing these processes in matrix form:
A ′ B ′ C ′ = − p 2 − 2 p − 1 − p − 1 0 − 1 0 0 × A B C
A B C = 0 0 − 1 0 − 1 p − 1 2 p − p 2 × A ′ B ′ C ′
It can easily be checked that these two matrices are the inverse of each other. (It may be simpler to notice that, for 3 × 3 triangular matrices of this type, the inversion formula is the following):
x y − 1 z − 1 0 − 1 0 0 − 1 = 0 0 − 1 0 − 1 − z − 1 − y − x − y z
Another interesting property of these matrices is that their determinate is − 1 . We could instead flip all the signs and have a determinate of 1, as this would not change the equations q ( x ) = 0 . However, we prefer this version as this way we obtain useful information from the sign of A i , as explained in Lemma 1.
Besides the fact that these matrices are inverses, it is also necessary to show that ⌊ x ⌋ = p . This can be seen by substituting the update formulas into the surd form:
x = − B + D A = − C ′ p + B ′ + D − C ′ = p + 1 / − C ′ B ′ + D = p + 1 / − C ′ B ′ + D = p + 1 / − C ′ ( − B ′ + D ) D − B ′ 2 = p + 1 / − B ′ + D A ′ = p + 1 / y
Hence, because we assumed x i + 1 = y > 1 , it follows that p is indeed the integer part of x when using the previous backwards update formulas. Hence let us now summarize this process and move onto the discussion of how to implement it.
Theorem 2
(Euler). A number x with a continued fraction representation [ p 1 ; p 2 , … , p m , ( p m + 1 ,   … , p m + n ) ] can also be represented as a surd.
We can exemplify this prepending process by generating the equation q ( x ) = 0 for x = [ 4 ; 5 , 6 , 7 ( 1 , … , 14 ) ] , given that we known that the equation for x = [ 7 ; ( 1 , … , 14 ) ] is 1 x 2 + 2 × 0 x − 61 = 0 . The resulting sequence of this process is the following:
i 1 2 3 4 5 … 15 16 = 5 … B i = − 245 , 725 11 , 341 − 366 0 − 7 … − 7 − 7   A i = 58 , 596 − 2195 61 1 12 … 1 12   C i = 1 , 030 , 459 − 58 , 596 2195 − 61 − 1 … 12 − 1   p i = 4 5 6 7 1 … 14 1  
This sequence is interesting as it illustrates cases where A i < 0 and | B i | > D = 61 . As stated in Lemma 3, when this occurs, we should have | B i | > | B i + 1 | . We do in fact observe a decreasing sequence of these values 245,725 > 11,341 > 336 > 0 .

3.2. GNU MP Implementation

We will now discuss how to implement the process described in Lemma 1 and how to detect the cycle proven in Theorem 1. The first observation is how to compute p i , the integer part of each surd x i . We initially calculate the value d = ⌊ D ⌋ and use this integer throughout the process to determine p i . If  A i > 0 , then we can use the following formula:
p i = − B i + D A i = − B i + ⌊ D ⌋ A i = − B i + d A i
Otherwise, if A i < 0 , we instead have the following formula:
p i = − B i + D A i = − B i + D A i = − B i + 1 + d A i
We used the multiple-precision library GNU MP (https://gmplib.org/). To represent the information necessary to a given state, we use the struct quadratic, which stores the A and B values., see Listing 1.
Listing 1. Structure for storing A and B values.
Mathematics 14 03447 i001
The value of D is instead kept as a global variable. As explained the value of D is kept constant throughout the process. The value of C is also kept as a global variable this time because it can be obtained from A, B, and D.
The function getC obtains the value of C = ( B 2 − D ) / A , as stated in Lemma 1, omitting the index i, see Listing 2. We use the variable ac to hold intermediate calculations. The result is stored in the global variable C.
Listing 2. Implementation of getC.
Mathematics 14 03447 i002
The function floorx is used to determine the integer parts p i according to the formulas in Equations (15) and (16). The global variables d and d p 1 store pre-computed values for ⌊ D ⌋ and ⌈ D ⌉ , respectively, see Listing 3.
Listing 3. Implementation of floorx.
Mathematics 14 03447 i003
The mpz_sgn function is used to check the sign of the corresponding integer. It returns − 1 , 0, or 1 when the sign is, respectively, negative, zero, or positive.
We now have the necessary components to implement the update process given in Equations (3) and (4). This is implemented in the function move, see Listing 4.
Listing 4. Implementation of move.
Mathematics 14 03447 i004
In this implementation we use Equation (4) to update B to B ′ . However, once this is carried out, we can no longer use Equation (3). Instead, we used the getC function, which gives − A ′ and then switches its sign.
It is fundamental to guarantee that the code executes correctly and does not output incorrect solutions or terminates unexpectedly. Towards this goal, we use the assert function to check that certain local properties hold. The argument of the function should always evaluate to true; otherwise, the function terminates the program to prevent incorrect outputs. In such cases it outputs the error message associated with the problem. In the context of this process, there are a couple of problematic cases that may occur. In the getC function, we need to check that A is a factor of B 2 − D , before computing an integer division. In the floorx function we need to check that A ≠ 0 , before computing the surd division. Note that this can be the result of an incorrect input or the next step from a computation where D is a perfect square. In essence, when D is a perfect square, the first call to the move function will yield A ′ = 0 . To see this, notice that in this case D = d 2 and the first integer part will be p = ( − B + d ) / A . Hence q ( p ) evaluates to ( A p + B ) 2 − D = ( − B + d + B ) 2 − d 2 = 0 . The last kind of error that we may encounter is the square root of a negative number, i.e., D < 0 . In fact, we need D > 0 , as  D = 0 is also problematic. The corresponding assert test is used in the discriminant function. (This function is omitted from the manuscript but is available in the git repository).
We consider two approaches to detect the cycle behavior. As a straightforward computational approach, we consider Floyd’s algorithm [5]. For this particular problem we can also consider a simple characterization of looping states, the Galois’s criteria.
First let us describe Floyd’s algorithm. The algorithm assumes that the discriminant function was computed, as this initializes the D, d, and dp1 global variables. Moreover, the Floyd function should not be called if the discriminant function reports any problem, see Listing 5. This may occur when D is a square or not positive. The algorithm keeps two states, h and t, also referred to as hare and turtle, respectively. The algorithms consists of two parts. In the first cycle both states use the move operation. However, the hare moves twice while the turtle one moves once. This difference in speed guarantees that the two states are always distinct while outside the cycle. Moreover, no matter the parity of the cycle size, the two states will eventually meet inside the cycle. At this point we found a state inside the cycle. Also, this state has some useful properties due to the process that was used to find it.
Listing 5. Implementation of Floyd’s algorithm.
Mathematics 14 03447 i005
Recall that the process starts at state q 1 . We use the copy function to duplicate the information from the argument q into the turtle and hare structs. There are m steps until the first state inside the cycle is reached, i.e., state q m + 1 . The size of the cycle is n, which means that q m + 1 = q m + 1 + n . In general, we have that q m + j = q m + j + k n , for any value j ≥ 1 and k ≥ 0 . To check if the hare and the turtle are in the same state, we use the equals function, which returns true if both the hare and turtle struct quadratic store the same information.
Let w represent the number of states traversed by the turtle inside the cycle and s be the total number of steps performed by the turtle. Clearly, the number of steps performed by the hare is 2 s . Hence we have the following equations:
m + w = s
m + w + k n = 2 s
In these equations, k represents the number of times the hare loops around the cycle. Subtracting the first equation from the second one, we conclude that k n = s = m + w . Hence the size of the cycle is a factor of the number of steps taken by the turtle. Also, it gives us a way to subtract w from s to obtain m. This is performed in the second part of the algorithm. This time, the turtle and the hare move in sync. The hare re-starts at the beginning of the process, but the turtle continues from the state q s + 1 . Hence, after m steps, the hare is at state q m + 1 and the turtle at state q m + 1 + s = q m + 1 + k n = q m + 1 . Therefore, both the hare and the turtle meet in the first state of the cycle. Hence we can determine the value of m; this is the return of the Floyd function. Moreover, the identified state q m + 1 is copied to the argument structure and therefore passed back to the caller function. We can determine the same state with the Galois function. Once we determine the state q m + 1 , we can simply move around the cycle to measure its size n. For this, we keep the turtle static and let the hare loop around the cycle. This is implemented by the Cycle function, see Listing 6.
Listing 6. Implementation of cycle.
Mathematics 14 03447 i006
Finally, note that all three of these functions receive an argument show that is used to printout the information related to the integer parts p i determined in the process. For example, for q 1 ( x ) = x 2 − 61 , we would obtain 7 (1 4 3 1 2 2 1 3 4 1 14).
To invoke Floyd’s algorithm, we instead use the letters F or D. In this case the input contains the coefficients A, B, and C or D depending on the given command. For example, both the following commands give the previous output.
  • F 1 0 -61
    D 1 0 61
Likewise, to invoke the same result with Galois’s criteria, we use the letters G or H. So the previous output can also be obtained with the following lines:
  • G 1 0 -61
    H 1 0 61
We also implemented the process described in Theorem 2. The addConvergent function updates the convergent information by applying Equation (6) to h i and k i . The struct convergent stores a pair of values for h and a pair of values for k, see Listing 7.
Listing 7. Structure for storing hi and ki values.
Mathematics 14 03447 i007
We interpret the index 1 in the C array as the index − 1 in our notation. Therefore, the value at index 0 is always the last computed value.
The addConvergent uses the mpz_addmul function to perform the desired computation, but the value is stored in the entry at index 1, see Listing 8. Therefore, it must be swapped to index 0 with the mpz_swap function. Once the convergents are computed, the coefficients A m + 1 , B m + 1 , and C m + 1 can be determined with Equation (8), see Listing 9. Our implementation simplifies A, B, and C so that their greatest common divisor is 1.
Listing 8. Implementation of addConvergent.
Mathematics 14 03447 i008
Listing 9. Coefficient computation according to Equation (8).
Mathematics 14 03447 i009
To implement the second part of Theorem 2, we use the function unmove, which implements the inverse of the move transformation, as described in Equation (14), see Listing 10.
Listing 10. Implementation of unmove.
Mathematics 14 03447 i010
For this second part, the numbers are given in reverse order. Hence, to obtain the example given before, we would input B 11 1 4 3 1 2 2 1 3 4 1 14 4 7 6 5 4.
The initial letter B indicates that we wish to build a polynomial. The number 11 is n. Next we input the 11 numbers that form the cycle 1 , … , 14 . Then the number 4 represents m. Finally, the numbers we want to prepend before the cycle are given in reverse order since the computation is performed backwards as explained before. The resulting polynomial is outputted as 58,596 x^2 -245,725 * 2x +1,030,459.
We will now consider Galois’s criterion as a more efficient process for identifying the states inside the cycle.
Lemma 7
(Galois). For any quadratic polynomial q i ( x ) defined in Lemma 1, if  A i > 0 , C i < 0 , and A i + C i > 2 B i , then x i is part of the cycle, i.e.,  i > m for the index m of Theorem 1.
This gives a much simpler implementation of the cycle detection procedure, implemented in the function Galois, see Listing 11. A schematic representation of the corresponding parabola is Given in Figure 2. The formal proof focus on x i ¯ , the small root of the parabola. The proof is given in Section 3.3.
Figure 2. Plot of q i ( x ) in the conditions of Lemma 7.
Listing 11. Implementation of Galois’ criterion.
Mathematics 14 03447 i011
For completeness, we recall a fundamental consequence of Galois’s criteria. Let us consider the integer parts in the continued fraction expansion of 61 . Note that, aside from the final value of 14 = 2 × 7 = 2 × ⌊ 61 ⌋ , the other coefficients inside the cycle form a palindrome, i.e.,  p 1 = p 11 , p 2 = p 10 , p 3 = p 9 , etc. This kind of structure occurs in general as described by the following theorem:
Theorem 3
(Galois). Given a non-square positive integer D, its regular continued fraction representation is of the form [ d : ( p 2 , … , p n , 2 d ) ] , where d = ⌊ D ⌋ , the size of the repeating values is n, and its initial part forms a palindrome, i.e.,  p 2 + i = p n − i for any i between 0 and n − 2 .
This result is proven by using the update formulas with generic values d and 2 d , forward and backward, respectively, and applying Lemma 7. The proof is given in Section 3.3. The theorem states that the continued fraction representation of D contains an initial term of d that is not part of the periodic portion. The periodic portion starts at p 2 , so according to our notation m = 1 . The  p i values in the periodic part always form an even palindrome followed by the value 2 d . We can observe this structure in our example, where D = [ 7 ; ( 1 , 4 , 3 , 1 , 2 , 2 , 1 , 3 , 4 , 1 , 14 ) ] . In this case, n = 11 , the initial part of the periodic portion contains the even palindrome formed from 1 , 4 , 3 , 1 , 2 and the value 14 = 2 × d , because  d = 7 . Likewise, 2 = [ 1 ; ( 2 ) ] , so d = 1 and the palindromic part is empty. The palindromic part may also be an odd palindrome, as in the case of 3 = [ 1 ; ( 1 , 2 ) ] , where again d = 1 .
As a final command we also implemented a solution to Pell’s equation. This is a Diophantine equation of the form x 2 − D y 2 = 1 , where D is a given non-square integer, and x and y are the sought-out integer solutions of the equation. In these conditions, Lagrange proved that Pell’s equation has infinitely many distinct integer solutions. These solutions approximate D by rational numbers of the form x / y . These approximations can be obtained from the convergents of the continued fractions of D . Our software outputs the fundamental solution, i.e., the one that minimizes x but is not the trivial solution x = 1 and y = 0 . This can be obtained using the P command. Therefore, the input P 61 results in the following output:
  • 1,766,319,049^2 - 61 * 226,153,980^2 = 1
Note that from the fundamental solution x , y , the remaining integer solutions x k , y k can be obtained from the following equation, where k is a natural number:
x k + y k D = ( x + y D ) k
Our implementation provides only the fundamental solution, which it obtains by computing the convergents of D and checking whether these values provide a solution to the equation.

3.3. Proofs

In this sub-section we give the proofs we omitted so far.
Proof of Lemma 1.
Most of the properties can be shown by induction. Clearly, in the base case, we have that x 1 > 1 can be represented as a surd, where A 1 = 1 , B 1 = 0 , and C 1 = − D are integers. The update formulas imply that A i + 1 , B i + 1 , and C i + 1 are also integers and that x i + 1 > 0 , as discussed in the text.
We will now explain why the chosen update formula guarantees that there is no need to keep track of the signal of the D term, i.e., that when A i > 0 then x i is the largest zero of q i ( x ) and when A i < 0 then x i is the smallest zero of q i ( x ) .
Let x ′ < x ″ be the two zeros of q i ( x ) . First assume that A i > 0 , in which case x i = x ″ . In this case, we have x ′ − p i < x ″ − p i . We have two cases. If  ⌊ x ′ ⌋ = p i , then x ′ − p i > 0 , in which case both terms are positive and we obtain that 1 / ( x ′ − p i ) > 1 / ( x ″ − p i ) = x i + 1 . Hence x i + 1 is the smaller zero of q i + i ( x ) so A i + 1 = − q i ( p i ) should be negative, which is necessarily the case because p i < x ′ and − q i ( x ) is a downwards-facing parabola. If  ⌊ x ′ ⌋ < p i , then x ′ − p i < 0 < x ″ − p i , and therefore 1 / ( x ′ − p i ) < 1 / ( x ″ − p i ) = x i + 1 . Hence x i + 1 is the larger zero of q i + i ( x ) , so A i + 1 = − q i ( p i ) should be positive. Which is the case because p i is in between zeros of q i ( x ) , i.e., x ′ < p i < x ″ , and  − q i ( x ) is a downwards-facing parabola.
Finally, we consider the case where A i < 0 . In this case, x i = x ′ < x ″ and therefore ⌊ x ′ ⌋ = p i . Therefore, x i − p i < x ″ − p i . In this case, both terms are positive as p i < x ′ < x ″ . Hence, by inverting the terms, the inequality changes, i.e.,  x i + 1 = 1 / ( x i − p i ) > 1 / ( x ″ − p i ) . Hence A i + 1 = − q i ( p i ) should be positive, which is necessarily the case because p i < x ′ and − q i ( x ) is an upwards-facing parabola.    □
Proof of Lemma 2.
For the first case we assume that A i > 0 and, by contradiction, that B i > D . Hence we conclude that x i = ( − B i + D ) / A i < 0 , which contradicts the hypothesis of Lemma 1 that x i > 1 .
For the second case we use a more elaborate deduction. Let us assume that A i < 0 and, by contradiction, that B i < − D . This implies that B i 2 > D and therefore that C i = ( B i 2 − D ) / A i < 0 , because  A i < 0 . Hence we have all the values of A i , B i , and C i strictly smaller than zero, i.e., A i < 0 , B i < 0 , and C i < 0 . Hence we get A i x 2 < 0 and 2 B i x < 0 for any x > 0 . We can then add all these inequalities to obtain that q ( x ) < 0 for any x ≥ 0 . Hence q ( x i ) = 0 must have x i < 0 , which also contradicts the hypothesis of Lemma 1 that x i > 1 .    □
Proof of Lemma 3.
To establish this property we consider the update formula of B i . To  handle both cases of the sign of B, we square both sides and obtain the following:
B i + 1 2 = ( A i p i + B i ) 2 = A i 2 p i 2 + 2 A i B i p i + B i 2 = A i p i ( A i p i + 2 B i ) + B i 2
Our goal is to show that B i 2 − B i + 1 2 > 0 , which implies the desired result | B i | > | B i + 1 | . From the above derivation we conclude that B i 2 − B i + 1 2 = − A i p i ( A i p i + 2 B i ) . We now split the analysis into cases. When A i > 0 , the first factor is smaller than zero, i.e.,  − A i p i < 0 . Moreover, from Lemma 2, we conclude that B i ≤ D . Recall that the hypothesis of Lemma 3 is that | B i | > D . Combining these two observations means that B i < − D . We can now show that A i p i + 2 B i < 0 with the following deduction:
A i p i + 2 B i < A i − B i + D A i + 2 B i = − B i + D + 2 B i = D + B i < D − D = 0
The other element of the deduction is the fact that p i is the largest integer that is smaller than the corresponding surd.
Now let us analyze the case when A i < 0 . In this case, − A i p i > 0 . Hence we need to show that A i p i + 2 B i > 0 . From the hypothesis of this lemma, we obtain that B i > D > 0 . We can combine this property with Lemma 2 and obtain the following deduction:
A i p i + 2 B i > A i − B i + D A i + 2 B i = − B i + D + 2 B i = D + B i > 0
Note that, for the first inequality, we have p i < ( − B i + D ) / A i combined with A i < 0 .    □
Proof of Theorem 1.
Consider again the sequence of surds x i described in Lemma 1. It follows from Lemma 3 that the coefficients B i must be taken from the finite amount of integers in the interval [ − D , D ] an infinite amount of times. To  see this, notice that since all B i are integers, Lemma 3 actually implies that if | B i | > D then | B i | − | B i + 1 | ≥ 1 . Hence iterating Lemma 3 means that if a given B i is outside this interval, it will become closer and closer to it until eventually, for some i ′ > i , it will be such that | B i ′ | ≤ D . Moreover, we can bound the value of index i ′ as i ′ − i ≤ | B i | − D .
Now let us focus on the whole surd x i , which depends on the values of A i and B i . Thus far we have studied B i since A i is even simpler to pin to a finite set of integers. Note that, in Lemma 1, we have the formula C i = ( B i 2 − D ) / A i , where C i is necessarily an integer. This implies that A i is a factor of B i 2 − D . Hence, for a fixed value of B i , there are only a finite amount of values that A i may assume. We thus conclude that the sequence of surds x i is such that the pairs of integers ( A i , B i ) return a infinite amount of times to a finite amount of possibilities and therefore the sequence must eventually repeat one such pair. Let us assume that this repetition occurs at indexes m + 1 and m + n + 1 , i.e., ( A m + 1 , B m + 1 ) = ( A m + n + 1 , B m + n + 1 ) . Now notice that the next state, A m + 2 and B m + 2 , can be uniquely determined from A m + 1 , B m + 1 , and D, see Lemma 1. Recall also that D is invariant throughout the process. Hence we conclude that this implies that ( A m + 2 , B m + 2 ) = ( A m + n + 2 , B m + n + 2 ) . Likewise, the same argument can be repeated any number of times, and it therefore implies that the whole process repeats indefinitely.    □
Proof of Lemma 4.
As argued before, we have that A m + 1 = 2 k m + n . By induction we can show that this value is greater than 0. This follows from the calculation formula and the fact that the p i values are positive. Hence A m + 1 > 0 . To conclude that these properties apply to all the coefficients A i , B i , and C i inside the cycle, and not just the very first one, note that the cycle can be rotated by swapping a suffix into a prefix. Our running example cycle is ( 1 , 4 , 3 , 1 , 2 , 2 , 1 , 3 , 4 , 1 , 14 ) , which can, for example, be rotated into ( 3 , 4 , 1 , 14 , 1 , 4 , 3 , 1 , 2 , 2 , 1 ) . Now the new quadratic polynomial q m + 1 ′ is actually the original quadratic polynomial q m + 8 . Thus this observation also applies to A m + 8 and in general to any of the quadratic polynomials inside the cycle. We can use the same argument for the sign of C i , since C m + 1 = − 2 h m + n − 1 < 0 .
Finally, we now have that A i C i < 0 . Therefore, B i 2 = D + A i C i implies B i 2 < D , which implies the desired property that | B i | < D .
Finally, note that the condition A i + C i > 2 B i reduces to checking that 2 k m + n − 2 h m + n − 1 > 2 ( k m + n − 1 − h m + n ) . This is the same as checking that k m + n + h m + n > k m + n − 1 + h m + n − 1 , which is true as both the k and h values are strictly increasing.    □
Proof of Lemma 5.
The property that C i + 1 < 0 follows directly from the update formula C i + 1 = − A i and the hypothesis A i > 0 .
For the property A i + 1 > 0 , we consider a schematic representation of q i ( x ) in the conditions of this lemma. We show such a scheme in Figure 1. The parabola faces upwards, because  A i > 0 . The  axis of the parabola is at x-coordinate − B / A . The parabola crosses the x-axis at two points and x i is the largest of the two. The integer p i is the floor of x i . According to the update Formula (3), we have that A i + 1 = − q i ( p i ) . Hence, to have A i + 1 > 0 , we need to show that p i occurs in the part where the parabola is below the x-axis. For this, it is enough to show that p i cannot be smaller than the small root. We will instead show the stronger claim that − B i / A i ≤ p i , as this is necessary to obtain the sign of B i + 1 .
Assume by contradiction that p i ≤ − B i / A i . We can then deduce that
− B i + D − A i A i = x i − 1 < p i ≤ − B i / A i
From this, it follows that D < A i 2 . From Lemma 1 we have that B i 2 − A i C i = D , but the hypothesis of Lemma 5 implies that − A i C i > 0 and therefore B i 2 < A i 2 . Therefore, we conclude that − B i / A i < 1 . Combined with the contradiction hypothesis, we conclude that p i < 1 , which is absurd.
Therefore, we must have − B i / A i < p i . This implies that A i + 1 > 0 . It also implies that B i + 1 < 0 . Recall the Formula (4), which is used to update the B coefficients. This formula is essentially B i + 1 = − q i ′ ( p i ) / 2 , where q i ′ ( x ) represents the derivative of q i ( x ) . Hence, to show that B i + 1 < 0 , it is enough to show that the derivative of q i ( x ) is positive at p i . This is true for all values larger than the axis, at  − B i / A i . Therefore, the result follows from the inequality we have just shown, − B i / A i < p i .
Recall that having − A i + 1 C i + 1 > 0 implies that B i + 1 2 < D and therefore we get the desired bounds that − D < B i + 1 < 0 .
For the last property, we will verify that A i + 1 − 2 B i + 1 + C i + 1 > 0 . According to the update Equation (13), we have the following derivation:
A i + 1 − 2 B i + 1 + C i + 1 = − A i p i 2 − 2 B i p i − C + 2 A i p i + 2 B i − A i = − ( A i ( p i 2 − 2 p i + 1 ) + 2 B i ( p i − 1 ) + C i ) = − q i ( p i − 1 )
Hence it is enough to show that q i ( p i − 1 ) is negative. By  Lemma 1 we have that 1 ≤ p i and therefore 0 ≤ p i − 1 . By looking at Figure 1, we can observe that q i ( x ) is negative for x in the interval [ 0 , p i ] . Since p i − 1 is in this interval, the desired property is true.    □
Proof of Lemma 7.
Let us assume by contradiction that the statement is false. Consider the largest value of i for which the property fails, i.e.,  q i ( x ) is not part of the cycle but  q i + 1 ( x ) is inside the cycle. Let p be the integer that is used to transition from q ( x ) to q ′ ( y ) , i.e., we have x = p + 1 / y . Because  q ′ ( y ) is inside the cycle, there will be some other polynomial q ″ ( z ) , which is also inside the cycle and that transitions to q ′ ( y ) , letting r be the integer that is used for this transition. Hence we have that z = r + 1 / y . From these two conditions we conclude that x − z = p − r . Note that all the polynomials, q ( x ) , q ′ ( y ) , and q ″ ( z ) , follow the scheme in Figure 2. The  polynomial q ( x ) , by this hypothesis, and the polynomials q ′ ( y ) and q ″ ( z ) , because of Lemma 4, as the states are inside the cycle. Hence x, y, and z are the largest roots of the corresponding equations.
Note that our hypothesis states that A > 0 , q ( 0 ) = C < 0 and q ( − 1 ) = A + C − 2 B > 0 . Hence Bolzano’s theorem implies that there is a root of q ( x ) in ] − 1 , 0 [ , see also Figure 1. This is not the root we are calculating, i.e., the largest root. Instead it is the smaller root, the one that contains the − D radical. We represent the smaller root as x ¯ , where the bar represents an automorphism  on Q [ D ] , that preserves Q and consists of changing the sign of D . For completeness, this notation represents the complex conjugate of x, and the fact that it is also a root of q ( x ) follows from the complex conjugate root Theorem [6]. Using these properties we have that x ¯ − z ¯ = x − z ¯ = p − r ¯ = p ¯ − r ¯ = p − r . Again, considering the scheme in Figure 2, we conclude that both x ¯ and z ¯ must lie in [ − 1 , 0 ] , in which case | x ¯ − z ¯ | < 1 . This implies that | p − r | < 1 and therefore p = r , as both p and r are integers. Hence the polynomials q ( x ) and q ″ ( z ) are the same and q ( x ) is inside the cycle with yields a contradiction.    □
Proof of Theorem 3.
Recall that the first polynomial used for the expansion of D is q 1 ( x ) = x 2 − D . From this polynomial we obtain q 2 ( x ) = ( D − d 2 ) x 2 − 2 d x − 1 , using the update described in Lemma 1. It is straightforward to check that q 2 ( x ) verifies Galois’s criteria, Lemma 7, as  D − d 2 > 0 , − 1 < 0 and D − d 2 − 1 ≥ 0 > − 2 d . Hence q 2 ( x ) is already inside the cycle and thus only the value p 1 = d is outside the cycle. We can now use q 2 ( x ) to obtain q n + 1 ( x ) by moving backwards, i.e., using the update in Equations (10)–(12), with  p = 2 d . This yields q n + 1 ( x ) = 1 x 2 + 2 ( d − 2 d ) x + d 2 − D − 4 d 2 + ( 2 d ) 2 = x 2 − 2 d x − ( D − d 2 ) . Hence we can observe that q 2 ( x ) and q n + 1 ( x ) are very similar; in fact, we can obtain one from the other by flipping the signs of the coefficients of x 2 and x 0 and swapping them with each other. This is the mirroring transformation we summarized in Lemma 6. Hence the sequence from q 2 ( x ) moving forward is the same as moving backwards from q n + 1 ( x ) . Thus the resulting sequence forms a palindrome.    □

4. Experiments

Our implementation, including the scripts we used to perform the following experiments are publicly available at https://github.com/LuisRusso-INESC-ID/RegularPICF (accessed on 6 July 2026).
We setup a couple of experiments to test the performance of our implementation. We expect the approach based on Floyd’s algorithm to always require O ( n + m ) steps both for determining n and m. However, Galois’s criteria require only O ( m ) steps to determine m and O ( m + n ) steps to determine n. Both algorithms need to store only a constant O ( 1 ) amount of states. However, the actual amount of bits necessary will be O ( 1 + log ( max A , B , C , D ) ) . Moreover, computing operations over large integers is also not constant. Adding or subtracting two b bit numbers requires O ( b / W ) time, where W is the size of the computer word. However, multiplication requires algorithms based on the FFT, see Schönhage and Strassen [7], and requires O ( ( b / W ) log b ) time. Hence each step of the algorithm actually has this complexity instead of constant time. Therefore, for b = ⌈ 1 + log ( max A , B , C , D ) ⌉ , the overall time performance of the algorithms will be O ( ( n + m ) ( b / W ) log b ) time for Floyd’s algorithm and O ( m ( b / W ) log b ) time for Galois’s criteria to determine m. Moreover, if we consider the initial processing step to compute a canonical surd, which may include a call to the mpz_gcd function, the overall time becomes O ( ( n + m + b ) ( b / W ) log b ) and O ( ( n + b ) ( b / W ) log b ) , respectively. The precise space bound of all these algorithms is just O ( b / W ) .
The tests were executed in a PC equipped with an Intel(R) Core(TM) i5-4278U CPU @ 2.60GHz and 7.6 GiB of RAM running Linux I 6.13.8-arch1-1. The algorithms are written in C and compiled with 14.2.1 20250207 with optimization flags -O9 and linked with the GMP version 6.3.0-2.
To measure the space and time resources we used the time command. It outputs both the “Elapsed real time (in seconds)” and the “Maximum resident set size of the process during its lifetime, in Kbytes.”. To guarantee time precision, the process is forced to run up to at least 5 s, repeating the calculation of the same input instance. The estimated time for each run was obtained by dividing the total time by the number of repetitions. The tests where executed with no background processes that might affect real-time performance.
Hence we first setup a sequence of tests to show the improvements provided by Galois’s criteria. We generate a sequence of polynomials for which m = 0 and n increases. These yield repeating continued fractions of the form [ ( 1 , … , 1 , 2 ) ] , i.e., where all entries of the repeating period are 1, except the last one, which is 2. The experimental results of this experiment are shown in Figure 3 and Figure 4. The space plot of Figure 4 confirms that the space requirements are essentially “constant” as n increases, i.e., are independent from the cycle size. The underlying performance function is not exactly constant and depends on the number of bits in the coefficients of q ( x ) , i.e., it is O ( 1 + log ( max A , B , C , D ) ) bits. In practice, in this test set, this value is constant. The time plot of Figure 3 confirms that Galois’s criteria are several orders of magnitude faster than the approach based on Floyd’s algorithm. Note that we plotted these result with a logarithmic y scale. Again, the time performance is not completely independent of n, but the impact is very small.
Figure 3. Time performance for fixed m = 0 .
Figure 4. Space performance for fixed m = 0 .
Likewise, to study configurations where the value of m increases and the value of n is always 1, we generate a sequence of polynomials. These generate repeating continued fractions of the form [ 1 ; … , 1 , ( 2 ) ] , i.e., where there is a big initial sequence of m entries equal to 1 and all entries of the repeating period are 2. The experimental results of this experiment are shown in Figure 5 and Figure 6. The space plot of Figure 6 again reinforces the claim that the space usage is essentially “constant” as m increases. The time plot of Figure 5 again shows that Galois’s criteria are faster. However, in this test case, both algorithms require only O ( m ) steps, so the resulting speedup revels the underlying hidden multiplicative factor. This is close to two, as Floyd’s algorithm performs twice the computation as it tracks two states, while Galois criteria only require one such state. Therefore, in this particular plot, we use a linear scale for the y-axis, instead of a logarithmic scale used for the similar case when m = 0 .
Figure 5. Time performance for fixed n = 1 .
Figure 6. Space performance for fixed n = 1 .
Moreover, to further highlight the computational cost of the underlying infinite precision operations, we tested the following continued fractions [ 8 10 , 000 × i , 2 ; … , 1 , ( 8 10 , 000 × i , … ,   8 10 , 000 × i , 1 ) ] . In these fractions, both m = 2 and n = 11 are fixed, but the size of the underlying integers increases. Inside the repeating portion, most of the coefficients are 8 10 , 000 × i , except the last one which is 1. The initial prefix consists of another 8 10 , 000 × i number followed by a 2. The resulting performance is shown in Figure 7 and Figure 8.
Figure 7. Time performance for fixed m = 2 and n = 11 .
Figure 8. Space performance for fixed m = 2 and n = 11 .
As expected in terms of space both algorithms present a very similar performance. But the constant associated with Floyd’s algorithm seems to be larger. This starts to show for very long integers but is not very significant. In terms of time, the difference favors Galois’ criterion much more. Note that n = 11 is the size of the size, where m = 2 is the size of the initial prefix. Because Galois’s criterion does not need to traverse the cycle, one would expect the performance difference between these to algorithms to be a factor of around 13 / 2 = 6.5 . The experimental factor for i = 100 is around 6, so the behavior is consistent with the expectation.
Finally, we added some tests where we choose a non-square value for D uniformly at random up to 2 i . The resulting performance is shown in Figure 9 and Figure 10. The resulting performance is similar to the fixed m tests. The space requirements store only a constant amount of integers whose size does not increase significantly. The time performance shows that Floyd’s algorithm is slower as the value of n should be around D log ( D ) . Recall that according to Theorem 3 the value of m in this data set is always 1.
Figure 9. Time performance for a random value of D ≤ 2 i .
Figure 10. Space performance for a random value of D ≤ 2 i .

5. Related Work

Theorem 1 was famously described and proved by Lagrange [8]. The original proof of the theorem was based on the convergence properties of regular continued fractions. Several other proofs based on similar principles exist, such as the ones from Charves [9] and Hermite [10].
Proofs that do not rely on convergence arguments were given by Ballieu [11], Gonçalves [12], and Perron [13,14]. These proofs make no reference to the convergence of the continued fraction and rely only on the formal algorithm, similar to the one explained in Lemma 1. In the algorithm described by Steinng [15], the sign of A i was not associated with the size of the zero of the corresponding quadratic polynomials and therefore the resulting cycle of polynomials could be twice as large as the ones we consider. These kinds of proofs are quite direct and require less computation than the earlier ones. A further simplified algorithmic proof was given by Steinng [15]. These proofs are essentially different from the one we present and moreover consider only the sequence of polynomial q i ( x ) and not, explicitly, the sequence of surds x i . An alternative proof, based on Dirichlet groups, is described by Karpenkov [16].
The palindromic structure of the repeating cycle was proven by Galois [17]. A bound on the size of the underlying cycles was proved by Hickerson [4]. This result was further improved by Stanton et al. [2] and Cohn [1], who provided the bound O ( D log D ) . Further studies of the statistical properties of the underlying cycles are also available [3,18].
Recent work on the stability of systems of rational difference equations with Pell coefficients was carried out by Ghe [19]. Also there is an interesting framework relating systems of nonlinear difference equations to generalized Fibonacci sequences given by Salman [20]. Note that the Fibonacci numbers appear as the sequence of cumulants when evaluating the purely periodic continued fraction [ ( 1 ) ] .
The algorithm for identifying general cycles in minimal space was given by Floyd, according to Knuth [5]. Several other alternatives exist, such as Brent’s algorithm [21], which has the same asymptotic performance as Floyd’s algorithm, but better hidden constants, that can improve experimental performance. Moreover, there is also Gosper’s algorithm. This is a sort of concurrent version of Brent’s algorithm. We chose Floyd’s algorithm as it is simple and requires minimal space and is thus a good alternative to something like a hash table, which also obtains optimal time but requires more space. For a more in-depth discussion of alternative methods consult the survey given by Nivasch [22]. For this specific problem, it is possible to identify in-cycle configurations using Galois’s Criteria [17].

6. Conclusions

We gave a detailed description of the process that is used to obtain the regular periodic continued fraction that represents D , where D is a non-square positive integer. Our description purposely unifies the surd and quadratic polynomial views of the process, as this approach allows us to give simple proofs of the basic properties of the process.
We naturally consider Lagrange’s theorem, which states that this process is bound to repeat. We give a new proof of this result, based only on combinatorial arguments, i.e., without resorting to convergence or analytical arguments.
We implement this process using the infinite precision library GMP. This allows us to experimentally study this process for arbitrarily large values. We consider two approaches to determine which states are initial and which states are part of the loop. Both approaches use only a constant amount of integers. Naive approaches of keeping lists of states were excluded as they would unnecessarily waste space. We consider two approaches, Floyd’s algorithm and Galois’s criteria. Our experimental results showed that Galois’s criteria are clearly the fastest approach.
Our implementation also includes routines to invert the given process, i.e., to determine a degree-two polynomial from a given regular periodic continued fraction. We added a routine to solve Pell’s equation and made the resulting software publicly available.
Several interesting mathematical results are related with this process, particularly, the bound on the size of the resulting loops O ( D log D ) . We expect this software can help in the study of this and other related problems. We may consider studying the size of the initial states in relation to the polynomial coefficients, or investigating the alternative cycles associated with a given discriminant D.

Funding

The work reported in this article was supported by national funds through Fundação para a Ciência e a Tecnologia (FCT), under project reference UIDB/50021/2020.

Data Availability Statement

The data presented in this study are openly available in RegularPICF at https://github.com/LuisRusso-INESC-ID/RegularPICF (accessed on 6 July 2026).

Acknowledgments

I am grateful the MIUP 2024 committee for stimulating my interest in Floyd’s algorithm. Also I would like to acknowledge the anonymous reviewers for several insightful comments and questions that largely improved that content of the manuscript, in particular it motivated the introduction of Lemma lem:mirror. Special thanks to the editorial team and staff at MDPI Mathematics for their dedication, professionalism, and support during the publication process.

Conflicts of Interest

The author declares no conflicts of interest.

References

  1. Cohn, J. The length of the period of the simple continued fraction of d1/2. Pac. J. Math. 1977, 71, 21–32. [Google Scholar] [CrossRef] [Scilit]
  2. Stanton, R.; Sudler, C.; Williams, H. An upper bound for the period of the simple continued fraction for D . Pac. J. Math. 1976, 67, 525–536. [Google Scholar] [CrossRef] [Scilit][Green Version]
  3. Battistoni, F.; Grenié, L.; Molteni, G. The first and second moments for the length of the period of the continued fraction expansion for d . Mathematika 2024, 70, 4. [Google Scholar] [CrossRef] [Scilit]
  4. Hickerson, D.R. Length of period simple continued fraction expansion of √d. Pac. J. Math. 1973, 46, 429–432. [Google Scholar] [CrossRef] [Scilit][Green Version]
  5. Knuth, D.E. The Art of Computer Programming; Seminumerical Algorithms; Exercises 6 and 7; Addison Wesley Longman Publishing Co., Inc.: Reading, MA, USA, 1969; Volume 2, 7p. [Google Scholar]
  6. Jeffrey, A. Complex Analysis and Applications, 2nd ed.; Taylor & Francis: Oxfordshire, UK, 2005. [Google Scholar]
  7. Schönhage, A.; Strassen, V. Schnelle Multiplikation großer Zahlen. Computing 1971, 7, 281–292. [Google Scholar] [CrossRef] [Scilit]
  8. Lagrange, J.-L. Additions au m moire sur la r solution des quations numériques. MéMoires L’AcadéMie R. Sci.-Belles-Lettres 1770, 24. [Google Scholar]
  9. Charves. Démonstration de la périodicité des fractions continues, engendrées par les racines d’une équation du deuxième degré. Bull. Sci. Math. Astron. 1877, 1, 41–43. [Google Scholar]
  10. Hermite, C. Sur La Théorie Des Fractions Continues; Cambridge University Press: Cambridge, UK, 2009; pp. 178–180. [Google Scholar]
  11. Ballieu, R. Sur le développement des irrationnelles quadratiques en fractions continues régulières. Mathesis 1942, 54, 304–314. [Google Scholar]
  12. Gonçalves, J.V. Sur les fractions continues réelles. Univ. Lisb. Rev. Fac. Ciências 1952, 2, 297–335. [Google Scholar]
  13. Hlawka, E.; Schoissengeier, J. Zahlentheorie: Eine Einführung; Manz: Vienna, Austria, 1979. [Google Scholar]
  14. Perron, O. Neue Periodizitätsbeweise für die regelmäßigen und halbregelmäßigen Kettenbrüche quadratischer Irrationalzahlen. Sitzungsber. Bayer. Akad. Wiss. Math.-Naturwiss. Kl. 1955, 1954, 321–333. [Google Scholar]
  15. Steinig, J. A proof of Lagrange’s theorem on periodic continued fractions. Arch. Math. 1992, 59, 21–23. [Google Scholar] [CrossRef] [Scilit]
  16. Karpenkov, O.N. Lagrange’s Theorem; Springer: Berlin/Heidelberg, Germany, 2022; pp. 129–138. [Google Scholar]
  17. Galois, É. Analyse algébrique. Démonstration d’un théorème sur les fractions continues périodiques. In Annales de Mathématiques Pures et Appliquées; Joseph-Diez Gergonne: Nîmes, France, 1828; Volume 19, pp. 294–301. [Google Scholar]
  18. Aka, M.; Shapira, U. On the evolution of continued fractions in a fixed quadratic field. J. D’Analyse Math. 2018, 134, 335–397. [Google Scholar] [CrossRef] [Scilit]
  19. Ghezal, A.; Zemmouri, I. Global stability of multi-dimensional system of rational difference equations of higher-order with Pell-coefficients. Bol. Soc. Parana. Mat. 2025, 43, 1–9. [Google Scholar] [CrossRef] [Scilit]
  20. Al Salman, H.J. Closed-form solutions of systems of nonlinear difference equations and their connections to generalized Fibonacci numbers and related sequences. AIMS Math. 2025, 10, 25307–25328. [Google Scholar] [CrossRef] [Scilit]
  21. Brent, R.P. An improved Monte Carlo factorization algorithm. BIT 1980, 20, 176–184. [Google Scholar] [CrossRef] [Scilit]
  22. Nivasch, G. Cycle detection using a stack. Inform. Process. Lett. 2004, 90, 135–140. [Google Scholar] [CrossRef] [Scilit]
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.

Article Metrics

Citations

Article Access Statistics

Multiple requests from the same IP address are counted as one view.