使用 JavaScript 查找丢番图方程的所有解
问题
我们需要编写一个接受数字n的JavaScript函数。我们的函数应该找到所有这样的数字x和y使得-
x^2 - 4y^2 = n.
它应该返回所有这些对的数组。
示例
以下是代码-
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));输出结果[ [ 45003, 22501 ], [ 9003, 4499 ], [ 981, 467 ], [ 309, 37 ] ]