All Euler problems
Project Euler

Diophantine Equation

Consider quadratic Diophantine equations of the form: x^2 - Dy^2 = 1 For example, when D = 13, the minimal solution in x is 649^2 - 13 x 180^2 = 1. It can be assumed that there are no solutions in...

Source sync Apr 19, 2026
Problem #0066
Level Level 03
Solved By 22,684
Languages C++, Python
Answer 661
Length 333 words
sequencemodular_arithmeticnumber_theory

Problem Statement

This archive keeps the full statement, math, and original media on the page.

Consider quadratic Diophantine equations of the form: \[x^2 - Dy^2 = 1\] For example, when \(D=13\), the minimal solution in \(x\) is \(649^2 - 13 \times 180^2 = 1\).

It can be assumed that there are no solutions in positive integers when \(D\) is square.

By finding minimal solutions in \(x\) for \(D = \{2, 3, 5, 6, 7\}\), we obtain the following: \begin {align*} 3^2 - 2 \times 2^2 &= 1\\ 2^2 - 3 \times 1^2 &= 1\\ {\color {red}{\mathbf 9}}^2 - 5 \times 4^2 &= 1\\ 5^2 - 6 \times 2^2 &= 1\\ 8^2 - 7 \times 3^2 &= 1 \end {align*}

Hence, by considering minimal solutions in \(x\) for \(D \le 7\), the largest \(x\) is obtained when \(D=5\).

Find the value of \(D \le 1000\) in minimal solutions of \(x\) for which the largest value of \(x\) is obtained.

Problem 66: Diophantine Equation

Mathematical Analysis

Pell’s Equation

The equation x2Dy2=1x^2 - Dy^2 = 1 is known as Pell’s equation. For non-square D>0D > 0, this equation always has infinitely many solutions in positive integers.

Connection to Continued Fractions

The fundamental (minimal) solution (x1,y1)(x_1, y_1) of Pell’s equation is obtained from the convergents of the continued fraction expansion of D\sqrt{D}.

Theorem: The continued fraction expansion of D\sqrt{D} is periodic:

D=[a0;a1,a2,,ar1,2a0]\sqrt{D} = [a_0; \overline{a_1, a_2, \ldots, a_{r-1}, 2a_0}]

where rr is the period length.

Theorem: Let pk/qkp_k / q_k denote the kk-th convergent of the continued fraction of D\sqrt{D}. Then the fundamental solution is:

  • If rr is even: (x1,y1)=(pr1,qr1)(x_1, y_1) = (p_{r-1}, q_{r-1})
  • If rr is odd: (x1,y1)=(p2r1,q2r1)(x_1, y_1) = (p_{2r-1}, q_{2r-1})

Convergent Computation

The convergents satisfy the recurrence:

pk=akpk1+pk2,qk=akqk1+qk2p_k = a_k p_{k-1} + p_{k-2}, \quad q_k = a_k q_{k-1} + q_{k-2}

with p1=1,p2=0p_{-1} = 1, p_{-2} = 0 and q1=0,q2=1q_{-1} = 0, q_{-2} = 1.

Continued Fraction Algorithm for D\sqrt{D}

Initialize: m0=0m_0 = 0, d0=1d_0 = 1, a0=Da_0 = \lfloor \sqrt{D} \rfloor.

Recurrence:

mn+1=dnanmnm_{n+1} = d_n a_n - m_n dn+1=Dmn+12dnd_{n+1} = \frac{D - m_{n+1}^2}{d_n} an+1=a0+mn+1dn+1a_{n+1} = \left\lfloor \frac{a_0 + m_{n+1}}{d_{n+1}} \right\rfloor

The period ends when an=2a0a_n = 2a_0.

Proof of Correctness

Claim: The fundamental solution of x2Dy2=1x^2 - Dy^2 = 1 is given by (pr1,qr1)(p_{r-1}, q_{r-1}) where rr is the period (or 2r2r if rr is odd).

Proof sketch:

  1. By Lagrange’s theorem, D\sqrt{D} has a periodic continued fraction.
  2. For any convergent pk/qkp_k/q_k, we have pk/qkD<1/(qkqk+1)|p_k/q_k - \sqrt{D}| < 1/(q_k q_{k+1}).
  3. If pk2Dqk2=1p_k^2 - D q_k^2 = 1, then (pk+qkD)(pkqkD)=1(p_k + q_k\sqrt{D})(p_k - q_k\sqrt{D}) = 1.
  4. The theory of continued fractions guarantees that the first such solution occurs at the end of the first period (or second period if the period is odd).

Editorial

We scan all non-square values of DD up to 10001000. For each one, we compute the period of the continued fraction of D\sqrt{D} and use its parity to determine which convergent yields the fundamental solution of Pell’s equation. We then generate convergents up to that index, extract the minimal numerator xx, and keep the value of DD for which this minimal xx is largest.

Pseudocode

Initialize the best pair as
    current best D = 0
    current best minimal x = 0

For each integer D from 2 through 1000:
    if D is a perfect square, move on to the next value

    compute the period length of the continued fraction of sqrt(D)
    from that parity, determine which convergent carries the fundamental solution

    regenerate the continued fraction up to the required convergent
    read off its numerator x

    if x is larger than the current best minimal x:
        replace the recorded best pair by (D, x)

Return the recorded value of D.

Complexity

  • Time: O(NPmax)O(N \cdot P_{\max}) where N=1000N = 1000 and PmaxP_{\max} is the maximum period length of any continued fraction for D1000D \le 1000.
    • The period length is O(DlogD)O(\sqrt{D} \log D) in the worst case.
  • Space: O(1)O(1) per DD (only need to track current and previous convergents).

Answer

661\boxed{661}

Code

Each problem page includes the exact C++ and Python source files from the local archive.

C++ project_euler/problem_066/solution.cpp
#include <bits/stdc++.h>
using namespace std;

// Big integer class (base 10^9) for Pell's equation
// Needed since minimal x can be ~10^37
struct BigInt {
    vector<int> d; // digits in base 10^9, least significant first

    BigInt() {}
    BigInt(long long v) {
        if (v == 0) d.push_back(0);
        while (v > 0) { d.push_back(v % 1000000000); v /= 1000000000; }
    }

    bool operator>(const BigInt& o) const {
        if (d.size() != o.d.size()) return d.size() > o.d.size();
        for (int i = (int)d.size()-1; i >= 0; i--)
            if (d[i] != o.d[i]) return d[i] > o.d[i];
        return false;
    }

    BigInt operator+(const BigInt& o) const {
        BigInt res;
        int carry = 0;
        for (int i = 0; i < (int)max(d.size(), o.d.size()) || carry; i++) {
            long long s = carry;
            if (i < (int)d.size()) s += d[i];
            if (i < (int)o.d.size()) s += o.d[i];
            res.d.push_back(s % 1000000000);
            carry = s / 1000000000;
        }
        return res;
    }

    BigInt operator*(long long v) const {
        BigInt res;
        long long carry = 0;
        for (int i = 0; i < (int)d.size() || carry; i++) {
            long long cur = carry;
            if (i < (int)d.size()) cur += (long long)d[i] * v;
            res.d.push_back(cur % 1000000000);
            carry = cur / 1000000000;
        }
        while (res.d.size() > 1 && res.d.back() == 0) res.d.pop_back();
        return res;
    }
};

// Solve Pell's equation x^2 - D*y^2 = 1 using continued fractions
// Returns the fundamental (minimal positive) solution x
BigInt solve_pell(int D) {
    int a0 = (int)sqrt((double)D);
    if (a0 * a0 == D) return BigInt(0); // perfect square

    // Find period length of continued fraction of sqrt(D)
    int m = 0, d = 1, a = a0;
    int period = 0;
    do {
        m = d * a - m;
        d = (D - m * m) / d;
        a = (a0 + m) / d;
        period++;
    } while (a != 2 * a0);

    // If period is even, solution is convergent p_{period-1}
    // If period is odd, solution is convergent p_{2*period-1}
    int target = (period % 2 == 0) ? period - 1 : 2 * period - 1;

    // Compute convergent p_{target}
    m = 0; d = 1; a = a0;
    BigInt pm2(1), pm1(a0); // p_{-1}=1, p_0=a0

    if (target == 0) return pm1;

    for (int i = 1; i <= target; i++) {
        m = d * a - m;
        d = (D - m * m) / d;
        a = (a0 + m) / d;

        BigInt pn = pm1 * a + pm2;
        pm2 = pm1;
        pm1 = pn;
    }

    return pm1;
}

int main() {
    ios_base::sync_with_stdio(false);

    BigInt max_x(0);
    int best_D = 0;

    for (int D = 2; D <= 1000; D++) {
        int s = (int)sqrt((double)D);
        if (s * s == D) continue;

        BigInt x = solve_pell(D);
        if (x > max_x) {
            max_x = x;
            best_D = D;
        }
    }

    cout << best_D << endl;

    return 0;
}