遞迴方法巧解不定方程

2021-08-21 22:45:52 字數 2870 閱讀 9775

多元一次方程往往採用迴圈求解。筆者在與網友們討論乙個問題(過程中,琢磨出一種演算法,採用遞迴進行多元一次方程的求解。並將解分為整數解和 非負整數解兩種情況,請大家指教。

private sub command1_click() '演示求x1+x2+x3+x4+x5=10整數解

text1.text = ""

dim answer as string

answer = getresult(5, 10, true) '賦值

dim temp

temp = split(answer, vbcrlf)

for i = 0 to ubound(temp)

temp(i) = "解" & i + 1 & ":" & vbtab & temp(i) ' add index

next

answer = join(temp, vbcrlf)

text1.text = "方程  x1+x2+x3+x4+x5=10 共有 " & ubound(temp) + 1 & " 個整數解:" & vbcrlf & answer 'show all answer in textbox

end sub

private sub command2_click() '演示求x1+x2+x3+x4+x5=10非負整數解

text1.text = ""

dim answer as string

answer = getresult(5, 10, false) '賦值

dim temp

temp = split(answer, vbcrlf)

for i = 0 to ubound(temp)

temp(i) = "解" & i + 1 & ":" & vbtab & temp(i) 'add index

next

answer = join(temp, vbcrlf)

text1.text = "方程  x1+x2+x3+x4+x5=10 共有 " & ubound(split(answer, vbcrlf)) + 1 & " 個非零整數解:" & vbcrlf & answer 'show all answer in textbox

end sub

private sub command3_click() '演示無解情況

text1.text = ""

dim answer as string

answer = getresult(5, 3, false)

dim temp

temp = split(answer, vbcrlf)

for i = 0 to ubound(temp)

temp(i) = "解" & i + 1 & ":" & vbtab & temp(i)

next

answer = join(temp, vbcrlf)

text1.text = "方程  x1+x2+x3+x4+x5=3 共有 " & ubound(split(answer, vbcrlf)) + 1 & " 個非零整數解:" & vbcrlf & answer

end sub

'求解函式

function getresult(byval n as integer, byval sum as integer, optional allowzero as boolean = true) as string

dim temp() as string, i as long

if n = 2 then '二元方程

if allowzero = true then

redim temp(sum)

for i = 0 to sum ' allow zero

temp(i) = "x1=" & i & ",x2=" & sum - i

next

getresult = join(temp, vbcrlf)

erase temp

else

redim temp(1 to sum - 1) 'forbid zero

for i = 1 to sum - 1

temp(i) = "x1=" & i & ",x2=" & sum - i

next

getresult = join(temp, vbcrlf)

erase temp

end if

end if

if n > 2 then

if allowzero = true then

redim temp(sum)

for i = sum to 0 step -1 ' allow zero

temp(i) = replace(getresult(n - 1, i, true), vbcrlf, ",x" & n & "=" & sum - i & vbcrlf) & ",x" & n & "=" & sum - i

next

getresult = join(temp, vbcrlf)

erase temp

else

if sum < n then msgbox "無解!": exit function '無解情況

redim temp(1 to sum - n + 1) 'not allow zero

for i = 1 to sum - n + 1

temp(i) = replace(getresult(n - 1, sum - i, false), vbcrlf, ",x" & n & "=" & i & vbcrlf) & ",x" & n & "=" & i '遞迴

next

getresult = join(temp, vbcrlf)

erase temp

end if

end if

end function

不定式方程求整數解(換分幣)

file name indefinite equation.c creat data 2015.1.23 author zy 不定式方程求整數解 換分幣 使用一元人民幣兌換成一分,兩分和五分的硬幣,共有多少種不同的兌換方法 include int main return 0 file name in...

不定式方程求整數解(愛因斯坦的數學題)

file name indefinite equation.c creat data 2015.1.23 author zy 不定式方程求整數解 愛因斯坦的數學題 愛因斯坦出了一道這樣的數學題,有一條長階梯,若每步 跨兩階,則剩最後一階,若每步跨三階,則最後剩兩階,若每步跨五階,則最後剩四階,若每步...

牛客練習49D 差分巧解區間 遞迴的處理

思路 看到這題,我腦海中浮現了一顆樹 每個葉子都是乙個1型別的操作。想到了n 2的演算法,記錄下每個操作時,之前所有操作的操作次數。dp i j i操作時,j操作一共執行了多少次 然而並沒有什麼用。看到題解發現真厲害 用字尾差分 tg i 記錄下第i次操作和第i 1次操作的運算元之差,每次遇到2的操...