ExcelVBAで行列でできる不定方程式の解法マクロを作る
この動画のマクロはWindows11/Office2016で作成してます。
不定方程式の解法マクロ
Excel futei.xlsm
Google 不定方程式を解いてみる
Sub macro()
a = 23
b = 31
c = 1
kai = tokutei(a, b)
Debug.Print "解 x= "; kai(1, 1) * c, " y= "; kai(1, 2) * c
End Sub
Function tokutei(a, b)
rt = ""
'a,bの符号を正にする
m_norm = Evaluate("{" & Sgn(a) & ",0;0," & Sgn(b) & "}")
v = Evaluate("{" & a & ";" & b & "}") 'aとbの列ベクトル
v = WorksheetFunction.MMult(m_norm, v)
Do
r = Int(v(1, 1) / v(2, 1))
q = v(1, 1) Mod v(2, 1)
If q = 0 Then
'割り切れた
Debug.Print "ユークリッドの互除法0"
Debug.Print "|" & Right(" " & v(1, 1), 4); "| = |"; Right(" " & r, 4); " 0 ||" & Right(" " & v(2, 1), 4); " |"
Debug.Print "|" & Right(" " & v(2, 1), 4); "| | 0 -1 ||"; Right(" " & q, 4); " |"
Debug.Print "最大公約数GCM", v(2, 1)
rt = r & "," & rt
Exit Do
Else
Debug.Print "ユークリッドの互除法1"
Debug.Print "|" & Right(" " & v(1, 1), 4); "| = |"; Right(" " & r, 4); " 0 ||" & Right(" " & v(2, 1), 4); " |"
Debug.Print "|" & Right(" " & v(2, 1), 4); "| | 0 -1 ||"; Right(" " & q, 4); " |"
Debug.Print
v(1, 1) = v(2, 1)
v(2, 1) = q
If rt = "" Then
rt = r
Else
rt = r & "," & rt
End If
End If
DoEvents
Loop
Debug.Print "商の並び ", rt
r = Split(rt, ",")
p = [{1,0;0,1}] '単位行列
For i = 0 To UBound(r) + 1
'逆行列をかけていく
If i > UBound(r) Then
s = m_norm
Else
s = Evaluate("{0,1;1,-" & r(i) & "}")
End If
p0 = WorksheetFunction.MMult(p, s)
Debug.Print "|" & Right(" " & p(1, 1), 4); " "; Right(" " & p(1, 2), 4); "| * |" & Right(" " & s(1, 1), 4); " "; Right(" " & s(1, 2), 4); "| = |" & Right(" " & p0(1, 1), 4); " "; Right(" " & p0(1, 2), 4); "|"
Debug.Print "|" & Right(" " & p(2, 1), 4); " "; Right(" " & p(2, 2), 4); "| |" & Right(" " & s(2, 1), 4); " "; Right(" " & s(2, 2), 4); "| |" & Right(" " & p0(2, 1), 4); " "; Right(" " & p0(2, 2), 4); "|"
Debug.Print
p = p0
DoEvents
Next
tokutei = p
End Function
0件のコメント