简体   繁体   中英

Finding solution set of a Linear equation?

I need to find all possible solutions for this equation:

x+2y = N , x<100000 and y<100000 .

given N=10 , say.

I'm doing it like this in python :

for x in range(1,100000):
    for y in range(1,100000):
        if x + 2*y == 10:
             print x, y

How should I optimize this for speed ? What should I do?

Essentially this is a Language-Agnostic question. A C/C++ answer would also help.

if x+2y = N , then y = (Nx)/2 (supposing Nx is even). You don't need to iterate all over range(1,100000)

like this (for a given N)

if (N % 2): x0 = 1
else: x0 = 0
for x in range(x0, min(x,100000), 2):
    print x, (N-x)/2

EDIT: you have to take care that Nx does not turn negative. That's what min is supposed to do

The answer of Leftris is actually better than mine because these special cases are taken care of in an elegant way

we can iterate over the domain of y and calculate x. Also taking into account that x also has a limited range, we further limit the domain of y as [1, N/2] (as anything over N/2 for y will give negative value for x)

x=N;
for y in range(1,N/2-1):
     x = x-2
     print x, y
  • This just loops N/2 times (instead of 50000)
  • It doesn't even do those expensive multiplications and divisions

This runs in quadratic time. You can reduce it to linear time by rearranging your equation to the form y = ... . This allows you to loop over x only, calculate y , and check whether it's an integer.

You may try to only examine even numbers for x given N =10 ; the reason is that: 2y must be even, therefore, x must be even. This should reduce the total running time to half of examining all x .

If you also require that the answer is natural number, so negative numbers are ruled out. you can then only need to examine numbers that are even between [0,10] for x , since both x and 2y must be not larger than 10 alone.

Calculate y by x . For integer positive x and real y :

for x in range(1,N):
        print (x, (N-x)/2)

Lefteris E 's answer is the way to go,

but I do feel y should be in the range [1,N/2] instead of [1,2*N]

Explanation:

x+2*y = N

//replace x with N-2*y
N-2*(y) + 2*y = N
N-2*(N/2) + 2*y = N
2*y = N

//therefore, when x=0, y is maximum, and y = N/2
y = N/2

So now you can do:

for y in range(1,int(N/2)):
   x = N - (y<<1)
   print x, y

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM