|
▼nekokai さん、G-Luckさん、おはようございます。
>
連立合同式の一般解は、
>x≡a(mod m)
>x≡b(mod n)
>の場合、mとnの最小公倍数+k という形になり、この「k」を解として表示させます。
>よって(n*k+b-a)がmで割って「1」余る「k」が得られるまで
私は、↑この文だけ見てアプローチしました。
つまり、0〜最小公倍数-1の数値の間で
mで割ってあまりがaかつ、nで割ってあまりがbになる値を求める方法です。
'===============================================================
Sub test()
Dim a As Variant
Dim b As Variant
Dim m As Variant
Dim n As Variant
Dim k As Variant
Dim gcd As Variant
a = Array(1, 2, 3, 0)
b = Array(7, 11, 13, 200)
m = Array(4, 9, 13, 29)
n = Array(11, 19, 33, 600)
' ↑4例をサンプルにしました
For idx = LBound(a) To UBound(a)
k = get_k(a(idx), b(idx), m(idx), n(idx), gcd)
If VarType(k) <> vbBoolean Then
MsgBox "x≡" & a(idx) & "(mod " & m(idx) & ")" & vbLf & _
"x≡" & b(idx) & "(mod " & n(idx) & ")" & vbLf & _
vbLf & "x≡" & k & "(mod " & gcd & ")"
Else
MsgBox "x≡" & a(idx) & "(mod " & m(idx) & ")" & vbLf & _
"x≡" & b(idx) & "(mod " & n(idx) & ")" & vbLf & _
vbLf & "error"
End If
Next idx
End Sub
'=======================================================================
Function get_k(a As Variant, b As Variant, m As Variant, n As Variant, gcd As Variant)
gcd = m * n / get_GCD(m, n)
'↑m,nの最小公倍数
ans = False
k = 0
Do While k < gcd
If (k Mod m) = a And (k Mod n) = b Then
ans = True
Exit Do
End If
k = k + 1
Loop
If ans = True Then
get_k = k
Else
get_k = False
End If
End Function
'===================================================================
Function get_GCD(n1 As Variant, n2 As Variant) As Long
'最大公約数を求める
Dim val1 As Long
Dim val2 As Long
Dim amari As Long
val1 = n1
val2 = n2
get_GCD = 1
Do While val2 <> 0
amari = val1 Mod val2
If amari = 0 Then
get_GCD = val2
End If
val1 = val2
val2 = amari
Loop
End Function
試してみてください
|
|