日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

等式成立JAVA_java – 找到两个线性等式成立的整数集

發布時間:2024/4/18 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 等式成立JAVA_java – 找到两个线性等式成立的整数集 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Reti43有正確的想法,但有一個快速的遞歸解決方案,對你的不等式有較少的限制性假設.

def solve(smin, smax, coef1, coef2):

"""

Return a list of lists of non-negative integers `n` that satisfy

the inequalities,

sum([coef1[i] * n[i] for i in range(len(coef1)]) > smin

sum([coef2[i] * n[i] for i in range(len(coef1)]) < smax

where coef1 and coef2 are equal-length lists of positive integers.

"""

if smax < 0:

return []

n_max = ((smax-1) // coef2[0])

solutions = []

if len(coef1) > 1:

for n0 in range(n_max + 1):

for solution in solve(smin - n0 * coef1[0],

smax - n0 * coef2[0],

coef1[1:], coef2[1:]):

solutions.append([n0] + solution)

else:

n_min = max(0, (smin // coef1[0]) + 1)

for n0 in range(n_min, n_max + 1):

if n0 * coef1[0] > smin and n0 * coef2[0] < smax:

solutions.append([n0])

return solutions

你會把它應用到這樣的原始問題上,

smin, coef1 = 185, (97, 89, 42, 20, 16, 11, 2)

smax, coef2 = 205, (98, 90, 43, 21, 17, 12, 3)

solns7 = solve(smin, smax, coef1, coef2)

len(solns7)

1013

而對于這樣的長期問題,

smin, coef1 = 185, (97, 89, 42, 20, 16, 11, 6, 2)

smax, coef2 = 205, (98, 90, 43, 21, 17, 12, 7, 3)

solns8 = solve(smin, smax, coef1, coef2)

len(solns8)

4015

在我的Macbook上,這兩種情況都在幾毫秒內完成.這應該可以很好地擴展到稍微大一些的問題,但從根本上說,它是系數N的O(2 ^ N).實際擴展的程度取決于附加系數的大小 – 更大的系數(與smax-相比) smin),解決方案越少,運行速度越快.

更新:從關于鏈接M.SE post的討論中,我看到這里兩個不等式之間的關系是問題結構的一部分.鑒于此,可以給出稍微簡單的解決方案.下面的代碼還包括一些額外的優化,可以在我的筆記本電腦上將8變量的解決方案從88毫秒加速到34毫秒.我已經嘗試了多達22個變量的示例,并在不到一分鐘的時間內得到了結果,但對于數百個變量來說,它永遠不會實用.

def solve(smin, smax, coef):

"""

Return a list of lists of non-negative integers `n` that satisfy

the inequalities,

sum([coef[i] * n[i] for i in range(len(coef)]) > smin

sum([(coef[i]+1) * n[i] for i in range(len(coef)]) < smax

where coef is a list of positive integer coefficients, ordered

from highest to lowest.

"""

if smax <= smin:

return []

if smin < 0 and smax <= coef[-1]+1:

return [[0] * len(coef)]

c0 = coef[0]

c1 = c0 + 1

n_max = ((smax-1) // c1)

solutions = []

if len(coef) > 1:

for n0 in range(n_max + 1):

for solution in solve(smin - n0 * c0,

smax - n0 * c1,

coef[1:]):

solutions.append([n0] + solution)

else:

n_min = max(0, (smin // c0) + 1)

for n0 in range(n_min, n_max + 1):

solutions.append([n0])

return solutions

您可以將它應用于這樣的8變量示例,

solutions = solve(185, 205, (97, 89, 42, 20, 16, 11, 6, 2))

len(solutions)

4015

該解決方案直接列舉有界區域中的晶格點.由于您需要所有這些解決方案,因此獲取它們所需的時間將與綁定的網格點的數量成比例(最多),這些網格點隨著維度(變量)的數量呈指數增長.

總結

以上是生活随笔為你收集整理的等式成立JAVA_java – 找到两个线性等式成立的整数集的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。