Finding all solutions of a Diophantine equation using JavaScript

Problem

We need to write a JavaScript function that takes a number n and finds all integer solutions (x, y) for the Diophantine equation:

x^2 - 4y^2 = n

The function should return an array of all such pairs [x, y].

Mathematical Approach

To solve x² - 4y² = n, we can factorize it as:

x^2 - 4y^2 = (x + 2y)(x - 2y) = n

Let a = x - 2y and b = x + 2y, then:

  • a × b = n
  • x = (a + b) / 2
  • y = (b - a) / 4

For integer solutions, both x and y must be integers.

Implementation

const findDiophantineSolutions = (num = 1) => {
    const solutions = [];
    let x, y;
    
    // Find all divisors of num
    for (let a = 1; a 

Solutions for x^2 - 4y^2 = 90005:
[ [ 45003, 22501 ], [ 9003, 4499 ], [ 981, 467 ], [ 309, 37 ] ]

Verification

Let's verify one of the solutions:

// Verify solution [309, 37]
const x = 309, y = 37;
const result = x * x - 4 * y * y;
console.log(`${x}^2 - 4 * ${y}^2 = ${result}`);
console.log(`Expected: 90005, Got: ${result}`);
console.log(`Correct: ${result === 90005}`);
309^2 - 4 * 37^2 = 90005
Expected: 90005, Got: 90005
Correct: true

Alternative Test Cases

// Test with smaller numbers
console.log("Solutions for n = 12:");
console.log(findDiophantineSolutions(12));

console.log("\nSolutions for n = 21:");
console.log(findDiophantineSolutions(21));

console.log("\nSolutions for n = 5:");
console.log(findDiophantineSolutions(5));
Solutions for n = 12:
[ [ 4, 1 ], [ 8, 2 ] ]

Solutions for n = 21:
[ [ 11, 5 ] ]

Solutions for n = 5:
[ [ 3, 1 ] ]

How It Works

  1. We iterate through all divisors a of n from 1 to ?n
  2. For each divisor a, we calculate b = n/a
  3. We check if x = (a + b)/2 is an integer using modulo operation
  4. We check if y = (b - a)/4 is an integer
  5. If both conditions are met, we add [x, y] to our solutions array

Conclusion

This algorithm efficiently finds all integer solutions to the Diophantine equation x² - 4y² = n by factorizing the equation and checking divisor pairs. The time complexity is O(?n) making it suitable for reasonable input sizes.

Updated on: 2026-03-15T23:19:00+05:30

313 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements