How to calculate the GCD (greatest common divisor) of two integers in VB.NET

4 Answers

0 votes
Imports System

Public Class Program
    Public Shared Sub Main(ByVal args As String())
        Dim a As Integer = 12, b As Integer = 20
        Dim i As Integer = 1, gcd As Integer
 
        While i <= a And i <= b
 
            If (a Mod i = 0 And b Mod i = 0) Then
                gcd = i
            End If
            i += 1
 
        End While
 
        Console.WriteLine("The GCD (greatest common divisor) of {0} and {1} is: {2}", a, b, gcd)
 
    End Sub
End Class



' run
'
' The GCD (greatest common divisor) of 12 and 20 is: 4
'

 



answered May 29, 2017 by avibootz
edited Aug 3, 2023 by avibootz
0 votes
Imports System

Public Class Program
    Public Shared Sub Main(ByVal args As String())
        Dim a As Integer = 12, b As Integer = 20
        Dim gcd As Integer
  
        Dim i As Integer = If(a < b, a, b)
  
        While i <= a And i <= b
  
            If (a Mod i = 0 And b Mod i = 0) Then
                gcd = i
                Exit While
            End If
            i -= 1
  
        End While
  
        Console.WriteLine("The GCD (greatest common divisor) of {0} and {1} is: {2}", a, b, gcd)
 
    End Sub
End Class



' run
'
' The GCD (greatest common divisor) of 12 and 20 is: 4
'

 



answered May 29, 2017 by avibootz
edited Aug 3, 2023 by avibootz
0 votes
Imports System

Public Class Program
	Public Shared Function gcd(a As Integer, b As Integer) As Integer
  		Return If(b = 0, a, gcd(b, a Mod b))
    End Function
		
    Public Shared Sub Main(ByVal args As String())
        Dim a As Integer = 12, b As Integer = 20
  
        Console.WriteLine("The GCD (greatest common divisor) of {0} and {1} is: {2}", a, b, gcd(a, b))
   
    End Sub
End Class



' run
'
' The GCD (greatest common divisor) of 12 and 20 is: 4
'

 



answered May 29, 2017 by avibootz
edited Aug 3, 2023 by avibootz
0 votes
Imports System

Public Class Program
    Public Shared Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer
        While b <> 0
            Dim temp As Integer = b
            b = a Mod b
            a = temp
        End While

        Return a
    End Function

    Public Shared Sub Main(ByVal args As String())
        Dim a As Integer = 12, b As Integer = 20
		
        Console.WriteLine("The GCD (greatest common divisor) of {0} and {1} is: {2}", a, b, gcd(a, b))
    End Sub
End Class



' run
'
' The GCD (greatest common divisor) of 12 and 20 is: 4
'

 



answered Aug 3, 2023 by avibootz
...