[英]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
. x+2y = N
, x<100000
并且y<100000
。
given N=10
, say. 假设N=10
。
I'm doing it like this in python : 我在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. C / C ++答案也有帮助。
if x+2y = N
, then y = (Nx)/2
(supposing Nx
is even). 如果x+2y = N
,则y = (Nx)/2
(假设Nx
是偶数)。 You don't need to iterate all over range(1,100000)
您不需要遍历整个range(1,100000)
like this (for a given N) 像这样(对于给定的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. 编辑:您必须注意Nx不会变成负数。 That's what min
is supposed to do 那是min
应该做的
The answer of Leftris is actually better than mine because these special cases are taken care of in an elegant way 实际上,Leftris的答案比我的要好,因为这些特殊情况得到了很好的解决。
we can iterate over the domain of y and calculate x. 我们可以遍历y的域并计算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的范围也有限,我们进一步将y的域限制为[1,N / 2](因为y的任何N / 2以上都会给x赋予负值)
x=N;
for y in range(1,N/2-1):
x = x-2
print x, y
This runs in quadratic time. 这以二次时间运行。 You can reduce it to linear time by rearranging your equation to the form y = ...
. 您可以通过将方程重新排列为y = ...
来将其减少为线性时间。 This allows you to loop over x
only, calculate y
, and check whether it's an integer. 这允许您仅循环x
,计算y
,并检查它是否为整数。
You may try to only examine even numbers for x
given N =10
; 给定N =10
,您可以尝试仅检查x
偶数; the reason is that: 2y
must be even, therefore, x
must be even. 原因是: 2y
必须是偶数,因此x
必须是偶数。 This should reduce the total running time to half of examining all x
. 这会将总运行时间减少到检查所有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. 然后,您只需检查x
[0,10]
之间的数字,因为x
和2y
必须不大于10
。
Calculate y
by x
. 用x
计算y
。 For integer positive x
and real y
: 对于正整数x
和实数y
:
for x in range(1,N):
print (x, (N-x)/2)
Lefteris E 's answer is the way to go, Lefteris E的答案是前进的道路,
but I do feel y
should be in the range [1,N/2]
instead of [1,2*N]
但我确实认为y
应该在[1,N/2]
范围内[1,N/2]
而不是[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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.