Purpose: Solve the Diophantine equation

for a given and , in — essentially one modular square root plus one Euclidean descent.

Algorithm

  1. Compute , a square root of modulo (via Tonelli-Shanks or Cipolla). If none exists, there is no solution. Take .
  2. Run the Euclidean algorithm on , stopping at the first remainder with .
  3. Let . If this is an exact integer square, the solution is ; otherwise no solution exists.

Code

// solve x^2 + d*y^2 = m ; returns {-1,-1} if no solution
pair<long long,long long> cornacchia(long long d, long long m) {
    long long r0 = tonelli((m - d % m + m) % m, m);   // sqrt(-d) mod m
    if (r0 < 0) return {-1, -1};
    if (2 * r0 < m) r0 = m - r0;                      // want m/2 < r0 < m
 
    long long a = m, b = r0, lim = (long long)sqrtl((long double)m);
    while (b > lim) { long long t = a % b; a = b; b = t; }
 
    long long rest = m - b * b;
    if (rest % d) return {-1, -1};
    long long s = (long long)sqrtl((long double)(rest / d));
    while (s * s < rest / d) s++;
    while (s * s > rest / d) s--;
    if (s * s * d + b * b != m) return {-1, -1};
    return {b, s};
}

Complexity

  • Time: — dominated by the modular square root
  • Space:

Why It Works

The Euclidean remainders of correspond to a reduction of the binary quadratic form of discriminant . Gauss’s theory of form reduction guarantees that if is representable by this form at all, the representation appears at exactly the first remainder dropping below . Everything else is verification.

Classic special cases

  • : sum of two squares. has a solution iff or (Fermat’s theorem on sums of two squares). Cornacchia constructs the representation, which the classical proof does not.
  • : Loeschian numbers. iff — the numbers representable as .
  • : iff .

Variants / Use Cases

  • Sum of two squares decomposition — the most common contest appearance; combine with a prime factorisation and the Gaussian-integer multiplication identity to represent composites
  • Sum of four squares — every positive integer is a sum of four squares (Lagrange); a randomised reduction plus Cornacchia gives an efficient construction
  • Counting lattice points on circles, the number of representations, follows from the factorisation of in
  • Complex multiplication / primality proving (ECPP) — Cornacchia finds the CM discriminant representation needed to build curves of known order
  • Quadratic residues — the theory the first step depends on