Pell equations

Pell equations

x² − Dy² = N. For D > 0 not a square the solutions come in finitely many families, each a fundamental solution multiplied over and over by the fundamental unit. Finding every family takes only a bounded search.

Families of solutions

Write α=x+yD\alpha = x + y\sqrt D, with norm N(α)=x2−Dy2N(\alpha) = x^2 - Dy^2. Norms multiply, so if α\alpha solves N(α)=NN(\alpha) = N and ε=x1+y1D\varepsilon = x_1 + y_1\sqrt D is the smallest solution of x2−Dy2=1x^2 - Dy^2 = 1, then every αεk\alpha\varepsilon^k is again a solution. Each class of solutions is one such orbit (up to sign), and there are finitely many classes.

Nagell's bounds say each class has a member with

0≤y≤N(x1−1)2D  (N>0),∣N∣D≤y≤∣N∣(x1+1)2D  (N<0), 0 \le y \le \sqrt{\frac{N(x_1 - 1)}{2D}} \ \ (N > 0), \qquad \sqrt{\frac{|N|}{D}} \le y \le \sqrt{\frac{|N|(x_1 + 1)}{2D}} \ \ (N < 0),

so a search over that range of yy finds every class. pellSolutions returns those fundamental solutions, the unit, and a solutions(count) that walks the orbits in increasing size.

import { pellSolutions } from "@ratmath/numtheory";

const r = pellSolutions(2, 7);
r.kind;                // "infinite"
r.unit;                // [3n, 2n]: 3² − 2·2² = 1
r.fundamental;         // [[3n, 1n], [3n, -1n]]: two classes
r.solutions(5);        // [[3n, 1n], [5n, 3n], [13n, 9n], [27n, 19n], [75n, 53n]]

pellSolutions(61, 1).unit;              // [1766319049n, 226153980n]
pellSolutions(13, -1).fundamental;      // [[18n, 5n]]
pellSolutions(3, 2).fundamental;        // []: x² − 3y² = 2 has no solutions (try mod 3)

When there are finitely many

For D<0D < 0 the form x2+∣D∣y2x^2 + |D|y^2 is positive definite, and for DD a perfect square k2k^2 it factors as (x−ky)(x+ky)(x - ky)(x + ky), so in both cases there are finitely many solutions and they are all listed.

pellSolutions(-1, 25).solutions.length;   // 12: the points of x² + y² = 25
pellSolutions(4, 5).solutions;           // [[-3n, -1n], [-3n, 1n], [3n, -1n], [3n, 1n]]

The same question in the language of number fields is the norm equation N(α)=nN(\alpha) = n in the order Z[D]\mathbb Z[\sqrt D]; normEquation is a second name for it. The general theory, with class groups, is on the quadratic forms page.

Try itEdit the code and run it with @ratmath/numtheory and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs