# 递归方法巧解不定方程（二）

1335人阅读 评论(0)

Private Sub Command1_Click()
Dim min(1 To 5) As Integer, max(1 To 5) As Integer, RESULT
min(1) = 2
min(2) = 3
max(1) = 3
max(2) = 7
jiefangcheng 5, min, max, 15

End Sub

'求解函数
Sub GETRESULT(ByVal n As Integer, ByRef min() As Integer, ByRef max() As Integer, ByVal SUM As Integer, Optional ByRef resultcount As Long, Optional ByRef RESULT)
Dim temp(), c() As Long, i As Long, j As Long, k As Long, r As Long

If n = 1 Then '一元方程
If SUM >= min(1) And SUM <= max(1) Then
resultcount = 1
ReDim RESULT(1 To 1, 1 To 1)
RESULT(1, 1) = SUM
End If
End If

If n > 1 Then
resultcount = 0
ReDim temp(min(n) To max(n))
ReDim c(min(n) To max(n))
For i = min(n) To max(n)
GETRESULT n - 1, min, max, SUM - i, c(i), temp(i)
resultcount = resultcount + c(i)
Next
If resultcount > 0 Then
ReDim RESULT(1 To resultcount, 1 To n)
For i = min(n) To max(n)
If c(i) > 0 Then
For j = 1 To UBound(temp(i), 1)
r = r + 1
For k = 1 To n - 1
RESULT(r, k) = temp(i)(j, k)
Next
RESULT(r, n) = i
Next
End If
Next
Erase temp
End If
End If

End Sub

Sub jiefangcheng(ByVal n As Integer, ByRef min() As Integer, ByRef max() As Integer, ByVal SUM As Integer, Optional ByRef RESULT)
Dim x() As String, i As Integer, msg As String, resultcount As Long, laptime As Single
laptime = Timer
'默认解的范围为1-SUM
For i = 1 To n
If min(i) = 0 Then min(i) = 1
If max(i) = 0 Then max(i) = SUM
Next

GETRESULT n, min, max, SUM, resultcount, RESULT '赋值

ReDim x(1 To n)
For i = 1 To n
x(i) = "X" & i
Next
msg = "方程" & Join(x, "+") & "=" & SUM

For i = 1 To n
x(i) = "X" & i & "∈[" & min(i) & "," & max(i) & "]"
Next
msg = msg & "当" & Join(x, ",") & " 时" '关于方程的表达式和解的定义域

If resultcount > 0 Then

Debug.Print msg & "共有 " & resultcount & " 个解"
ReDim x(1 To resultcount)
For i = 1 To resultcount
x(i) = "解" & i & "："
For j = 1 To n
x(i) = x(i) & "X" & j & "=" & RESULT(i, j) & vbTab
Next
Next
Debug.Print Join(x, vbCrLf)
Else

Debug.Print msg & "无解！"
End If
laptime = Timer - laptime
Debug.Print "总计用时" & IIf(laptime < 0, 0, Format(laptime, "0.000")) & "秒！"
End Sub

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：638608次
• 积分：8286
• 等级：
• 排名：第2481名
• 原创：205篇
• 转载：26篇
• 译文：1篇
• 评论：213条
评论排行
最新评论