Search code examples
vb.netlcm

How can I get the LCM of 2 numbers without GCD?


I'm trying to make a Fraction Calculator in VB.NET, but I'm stuck with the LCM part. I found some code on the internet:

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

But when I'm trying to get the LCM, it shows me the second number every time! e.g When I try to get the LCM of 2 and 3 it shows me 3.

How can I get the LCM without GCD?


Solution

  • Found this on the internet

    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