Home  >  Article  >  Web Front-end  >  JavaScript Fun Question: Diophantine Equation

JavaScript Fun Question: Diophantine Equation

黄舟
黄舟Original
2017-01-22 15:00:151586browse

In mathematics, the Diophantine equation is a polynomial equation that usually has two or more unknowns and requires their integer solutions.

Given the following Diophantine equation, find all its positive integer solutions.

x² - 4y² = n

x and y are unknowns, and n is a given constant. The solution set of x, y will be displayed using the following nested array:

[[x1, y1], [x2, y2] ....]

Here are some examples:

sol_equa(90005) --> [[45003, 22501], [9003, 4499], [981, 467], [309, 37]]

sol_equa(90002) --> []

Let’s see how to solve this problem. First look at the left side of this equation, x² - 4y². At first glance, you will have a feeling that it can be transformed is (x - 2y) * (x + 2y), when you think of this, you have taken the first step.

Because the constant N on the right side of the equation may be a very large number, if the exhaustive method is used, the efficiency is very low.

We can try to decompose this constant and factor it into two terms.

For example, N=24, it can be decomposed into two items as follows:

[1,24], [2,12], [3,8], [4,6 ]

We use these possibilities to apply it to the formula:

x - 2y = 1

x + 2y = 24

----- ---------

x - 2y = 2

x + 2y = 12

......

This way It is transformed into finding a linear equation of two variables.

Finally, we can select the positive integer solution.

function solequa(n) {  
    var result = [];  
    for(var a=1,b=n;a<=b;a++){  
        if(n % a == 0){  
            b = n / a;  
            var x = (a + b) / 2;  
            var y = (b - a) / 4;  
            if(parseInt(x) == x && parseInt(y) == y && x >=0 && y >= 0){  
                result.push([x,y]);  
            }  
        }  
    }  
    return result;  
}

The above is the content of JavaScript interesting question: Diophantine equation. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn