Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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 −
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 ] ]
Advertisements
