GCD of two numbers

This code shows how to find the GCD of two numbers.


Private Sub GCD()
Dim intFirst, intSecond As Integer
Dim strOutput As String

intFirst = 200
intSecond = 500
strOutput = "GCD of " & intFirst & " AND " & intSecond & " is "

If intFirst = 0 And intSecond = 0 Then
'If both numbers are 0 then no gcd.
MessageBox.Show("No GCD")
Exit Sub
ElseIf intFirst = 0 And intSecond <> 0 Then
'If first number is 0 and second is greater than 0
'than second number is gcd.
MessageBox.Show(strOutput & intSecond)
Exit Sub
ElseIf intFirst <> 0 And intSecond = 0 Then
'If first number is greater than 0 and second is 0
'than first number is gcd.
MessageBox.Show(strOutput & intFirst)
Exit Sub
Else
'Subtract the smaller value from the greater value till
'both numbers are equal.
While intFirst <> intSecond
If (intFirst > intSecond) Then
intFirst = intFirst - intSecond
Else
intSecond = intSecond - intFirst
End If

End While
End If
MessageBox.Show(strOutput & intFirst)
End Sub


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: