Finding all solutions of a Diophantine equation using JavaScript

JavascriptWeb DevelopmentFront End Technology

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 ] ]
raja
Published on 19-Apr-2021 11:01:55
Advertisements