2x 4y 6z = 1200
x y z = 300
如何在 ac# 方法中找到可能的x, y,z 整數值?,我試圖找到一個更好的解決方案,而不是使用嵌套 for 回圈的蠻力 ,因為它不是一個好的解決方案。
public List<Tuple<int, int, int>> Calculate()
{
var result = new List<Tuple<int, int, int>>();
int maxValue = 300;
for(int i = 0; i< maxValue; i )
for (int j = 0; j < maxValue; j )
for (int k = 0; k < maxValue; k )
if (i j k == maxValue && 2 * i 4 * j 6 * k == 1200)
result.Add(new Tuple<int, int, int>(i, j, k));
return result;
}
先感謝您。
uj5u.com熱心網友回復:
嗯,有
2x 4y 6z = 1200
x y z = 300
你可以把它當作
x 2y 3z = 600
x y z = 300
從第一個減去第二個,你得到
y 2z = 300
或者
y = 300 - 2z
因為x = 300 - y - z我們可以把它當作
x = 300 - y - z =
= 300 - (300 - 2z) - z =
= 300 - 300 2z - z =
= z
最后,對于任意 z(這是自由變數)
x = z
y = 300 - 2 * z;
可能的c#代碼:
private static (int x, int y, int z) Solution(int x) => (x, 300 - 2 * x, x);
演示:
string solutions = string.Join(Environment.NewLine, Enumerable
.Range(0, 10)
.Select(x => Solution(x)));
...
// 10 solutions for x = 0..9
string solutions = string.Join(Environment.NewLine, Enumerable
.Range(0, 10)
.Select(x => Solution(x)));
Console.Write(solutions);
結果:
(0, 300, 0)
(1, 298, 1)
(2, 296, 2)
(3, 294, 3)
(4, 292, 4)
(5, 290, 5)
(6, 288, 6)
(7, 286, 7)
(8, 284, 8)
(9, 282, 9)
如果您只尋找非負解決方案(您在代碼的注釋中提到了概率),那么x在[0..150]范圍內使用:
(0, 300, 0)
(1, 298, 1)
(2, 296, 2)
...
(148, 4, 148)
(149, 2, 149)
(150, 0, 150)
編輯:您的Calculate()方法改進:
public static List<Tuple<int, int, int>> Calculate() {
var result = new List<Tuple<int, int, int>>();
const int maxValue = 300;
int start = Math.Max(150 - maxValue / 2, 0);
for (int x = start; ; x) {
int y = 300 - 2 * x;
int z = x;
if (y < 0 || x > maxValue)
break;
result.Add(new Tuple<int, int, int>(x, y, z));
}
return result;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/406021.html
標籤:
上一篇:當Python因為我無法單擊串列而不允許我單擊任何內容時,如何在Python中使用selenium來選擇日歷日期?
