[英]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 包括在內。
這個問題相當於一種硬幣找零問題 - 用一些名義值(此處為 1,2,3,4)獲得有限數量(此處最多 29 個)硬幣的總和
進行所有更改的最簡單方法是遞歸生成。
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 個嵌套循環
還存在動態編程方法 - 用可能的組合填充表 [0..sum](為了獲得所有可能的組合,DP 並不快)
這個方程有無限個解,因為它代表了某個 4d 空間中的一個平面,並且該平面上的所有點都是有效的解。
為了有一個唯一的解,你至少需要 4 個這樣不同的方程,但是仍然不能保證在那之后你會得到這些方程組的解。
由於有效數字的范圍很小(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 乘以 bt 1= 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.