Hi!all
Im having a diffucult time to spot the error on the below codes to find the GCD of the two integer numbers.Please help me to debug

Private Sub cmdgcd_Click()

Dim A As Integer, B As Integer, D As Integer
A = InputBox("A = ?")
B = InputBox("B = ?")
D = GCD(A, B)
MsgBox ("The GCD of " & A & " and " & B & " is " & D)
End Sub
Function GCD(ByVal X As Integer, ByVal Y As Integer) As Integer
Dim R As Integer
Do While Y > 0
R = X Mod Y
X = Y
Y = R
Loop


End Function

Thanx alot

Recommended Answers

All 3 Replies

Stick this outside any subs (in a module, or the bottom of a form OUTSIDE of any of the existing code)

Public Function GCD_Of(First_Int, Second_Int)
W = "ERROR: "
Err1 = "Invalid numeric argument(s)"
Err2 = "Argument(s) must be non-zero"
     
Q = CDec(1) ' Initialize quotient as DECIMAL variable type
R = Q       ' Initialize remainder
    
' Read the input argument values
X = First_Int
Y = Second_Int
  
If IsNumeric(X) = False Or IsNumeric(Y) = False Then
	GCD_Of = W & Err1
	Exit Function
End If
  
' Convert input arguments into DECIMAL variable type
X = CDec(X)
Y = CDec(Y)
   
' Report error if argument(s) non-integer
If InStr(X, ".") > 0 Or InStr(Y, ".") > 0 Then
	GCD_Of = W & Err1
	Exit Function
End If
   
' Make sure both arguments are absolute values
If X < 0 Then X = -X
If Y < 0 Then Y = -Y
   
' Report error if either argument is zero
If X = 0 Or Y = 0 Then GCD_Of = W & Err2: Exit Function
  
' Swap argument values, if necessary, so that X > Y
If X < Y Then Q = X: X = Y: Y = Q
  
' Perform Euclid's algorithm to find GCD of X and Y
While R <> 0
	Q = X / Y
        i = InStr(Q, ".")
	If i > 0 Then Q = Left(Q, i - 1)
        R = X - Q * Y
        X = Y
        Y = R
Wend
  
' Return the result
GCD_Of = X
  
End Function

Stick This in your button or form load or wherever you plan to use it:

Dim A As Integer, B As Integer, D As Integer
A = InputBox("A = ?")
B = InputBox("B = ?")
D = GCD_of(A, B)
MsgBox ("The GCD of " & A & " and " & B & " is " & D)
End Sub

You are so close, you have it solved, but your problem is that you need one last line of code for your GCD function:

GCD = X
End Function

You are so close, you have it solved, but your problem is that you need one last line of code for your GCD function:

GCD = X
End Function

Thanks for helping. I'm sure the OP has been waiting for the past 6 years for you add that piece of info so he can finish his project. :icon_rolleyes:

commented: :) +13
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.