Answer the question
In order to leave comments, you need to log in
How to improve the algorithm for the Diophantus equation?
There is Diophantus's equation -
x2 - 4 * y2 = nfrom https://www.codewars.com/kata/554f76dca89983cc4000... .
function solequa(n) {
// your code
let pt1 = 1 //pointer 1
let pt2 = 1 // pointer 2
let result = 0
const sqrtN = Math.sqrt(n)
const diapason = [sqrtN , sqrtN+1]
while (pt2 < n ) {
result = pt1/pt2;
console.log(pt1,pt2)
const solve = pt1*pt1-4*pt2*pt2
if (result < diapason[0]){
pt1 = pt1+ 1
} else if (result > diapason[1]) {
pt2 = pt2 + 1
} else if (solve === n) {
console.log("solved with " + pt1 + " "+ pt2)
return [pt1,pt2]
} else {
pt1 = pt1+ 1
}
}
}
solequa(5)
Answer the question
In order to leave comments, you need to log in
The logic behind your decision is completely incomprehensible. Some greedy shifts of one of the two variables by 1, and even the answer will return exactly once, when, as in the problem, you need to find all the solutions to the equation.
There, according to your link in the problem, there is a hint: the equation can be rewritten in the form (x-2y)(x+2y)=n
This gives the solution: Go through all the divisors of n that do not exceed the root. Let the divisor be d, then the second factor will be n/d.
It remains to solve the system of linear equations:
x-2y=d
x+2y=n/d
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question