没有GCD如何得到2个数的LCM?
How can I get the LCM of 2 numbers without GCD?
我正在尝试在 VB.NET 中制作一个分数计算器,但我被 LCM 部分卡住了。我在网上找到了一些代码:
Public Shared Function GCD(a As Integer, b As Integer) As Integer
If a = 0 Then
Return b
End If
Do While b <> 0
If a > b Then
a = a - b
Else
b = b - a
End If
Loop
Return a
End Function
Public Shared Function LCM(a As Integer, b As Integer) As Int64
Return Math.BigMul(Math.Abs(a), Math.Abs(b)) \ GCD(a, b)
End Function
但是当我尝试获取 LCM 时,它每次都显示第二个数字!例如,当我尝试获取 2 和 3 的 LCM 时,它显示 3.
没有GCD如何获取LCM?
在网上找到的
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim _lcm As Integer = lcm(140, 72)
_lcm = lcm(2, 3)
End Sub
Public Function lcm(a As Integer, b As Integer) As Integer
If a = 0 OrElse b = 0 Then
Return 0
End If
Dim _gcd As Integer = gcd(a, b)
Return CInt((a * b) / _gcd)
End Function
Public Function gcd(a As Integer, b As Integer) As Integer
If a < 1 Or b < 1 Then
Throw New ArgumentException("a or b is less than 1")
End If
Dim _a As Integer = Math.Max(a, b)
Dim _b As Integer = Math.Min(a, b)
Dim r As Integer = 0
Do
r = _a Mod _b
_a = _b
_b = r
Loop While _b <> 0
Return _a
End Function
我正在尝试在 VB.NET 中制作一个分数计算器,但我被 LCM 部分卡住了。我在网上找到了一些代码:
Public Shared Function GCD(a As Integer, b As Integer) As Integer
If a = 0 Then
Return b
End If
Do While b <> 0
If a > b Then
a = a - b
Else
b = b - a
End If
Loop
Return a
End Function
Public Shared Function LCM(a As Integer, b As Integer) As Int64
Return Math.BigMul(Math.Abs(a), Math.Abs(b)) \ GCD(a, b)
End Function
但是当我尝试获取 LCM 时,它每次都显示第二个数字!例如,当我尝试获取 2 和 3 的 LCM 时,它显示 3.
没有GCD如何获取LCM?
在网上找到的
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim _lcm As Integer = lcm(140, 72)
_lcm = lcm(2, 3)
End Sub
Public Function lcm(a As Integer, b As Integer) As Integer
If a = 0 OrElse b = 0 Then
Return 0
End If
Dim _gcd As Integer = gcd(a, b)
Return CInt((a * b) / _gcd)
End Function
Public Function gcd(a As Integer, b As Integer) As Integer
If a < 1 Or b < 1 Then
Throw New ArgumentException("a or b is less than 1")
End If
Dim _a As Integer = Math.Max(a, b)
Dim _b As Integer = Math.Min(a, b)
Dim r As Integer = 0
Do
r = _a Mod _b
_a = _b
_b = r
Loop While _b <> 0
Return _a
End Function