Q
Q
Quintis2021-03-23 10:32:53
JavaScript
Quintis, 2021-03-23 10:32:53

How to improve the algorithm for the Diophantus equation?

There is Diophantus's equation -

x2 - 4 * y2 = n
from https://www.codewars.com/kata/554f76dca89983cc4000... .

Here is my code to solve this equation :
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)

For small numbers it works fine, but for solequa(16) the algorithm can't find a solution. Who can help to make the correct algorithm

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-03-23
@Quintis

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

It is solved in the mind - x=(d+n/d)/2, y=(n/dd)/4
It was only necessary to take into account the Diophantine equation - the answer must be non-negative integers. So, it is necessary that both divisors d, n / d give the same remainder after dividing by 4 and 2. Well, d <= n / d, but this will be taken into account by enumeration of the divisor to the root.
That's the whole solution - loop through the divisor up to the root, make sure that it and the remaining factor give the same remainder modulo 4, calculate x and y and output them.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question