Finding all solutions of a Diophantine equation using JavaScript


Problem

We are required to write a JavaScript function that takes in a number n. Our function should find all such number x and y such that −

x^2 - 4y^2 = n.

And it should return an array of all such pairs.

Example

Following is the code −

 Live Demo

const num = 90005;
const findSolution = (num = 1) => {
   const res = [];
   let a, b;
   for(let a = 1; a <= Math.sqrt(num); a++){
      if(Number.isInteger(b = num/a)){
         if(Number.isInteger(x = (b+a)/2)){
            if(Number.isInteger(y = (b-a)/4)){
               res.push([x, y]);
            };
         };
      };
   };
   return res;
};
console.log(findSolution(num));

Output

[ [ 45003, 22501 ], [ 9003, 4499 ], [ 981, 467 ], [ 309, 37 ] ]

Updated on: 19-Apr-2021

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements