如何求解 4 个变量的方程

How to solve an equation for 4 variables

说我有

    a + 3b + 4c +2d =40; 

我如何解决a,b,c和d。 我不确定从哪里开始,我正在使用 C 语言对此进行编码。我知道一种解决方案是 a=9 b=3 c=2 d=7.

我忘了补充一点,a、b、c、d 的域是 0-29(含)。

这个方程有无穷多个解,因为它代表了一个 4d space 的平面,并且该平面上的所有点都是有效解。

为了求得唯一解,你至少需要4个这样的不同方程,但仍不能保证你能得到这组方程组的解。

这个问题等同于硬币找零问题——用有限数量(这里最多 29 个)的硬币和一些标称值(这里是 1、2、3、4)求和

进行所有更改的最简单方法是递归生成。

 makesum(coinlist, currentsum, resultlist)
      if currensum < 0
           return

      if currensum = 0
           print resultlist

      for coin in coinlist
          makesum(coinlist - coin, currentsum - coinvalue, resultlist + coin)

对于特定情况 - 小的固定标称列表 - 你可以只做 4 个嵌套循环

还存在动态规划方法 - 用可能的组合填充 table[0..sum](为了获得所有可能的组合,DP 并不更快)

由于有效数字的范围很小 (0-29),您可以使用蛮力,即 4 个 for 循环,并打印所有解决方案:

#include <stdio.h>

int main(void) {
    for (int a=0; a<30; ++a)
        for (int b=0; b<30; ++b)
            for (int c=0; c<30; ++c)
                for (int d=0; d<30; ++d)
                    if (a + 3*b + 4*c + 2*d == 40)
                        printf("Solution: a=%d b=%d c=%d d=%d\n", a, b, c, d);
    return 0;
}

输出:

Solution: a=0 b=0 c=0 d=20
Solution: a=0 b=0 c=1 d=18
Solution: a=0 b=0 c=2 d=16
Solution: a=0 b=0 c=3 d=14
Solution: a=0 b=0 c=4 d=12
Solution: a=0 b=0 c=5 d=10
Solution: a=0 b=0 c=6 d=8
Solution: a=0 b=0 c=7 d=6
Solution: a=0 b=0 c=8 d=4
Solution: a=0 b=0 c=9 d=2
Solution: a=0 b=0 c=10 d=0
Solution: a=0 b=2 c=0 d=17
Solution: a=0 b=2 c=1 d=15
Solution: a=0 b=2 c=2 d=13
. . .
<many more solutions>
. . .

如果你想要 1 的答案,方程是三乘以 y = 三除以三 =1 和 y=1 所以答案是 3 乘以 1= 3