Quantcast
Channel: VBForums - CodeBank - Visual Basic 6 and earlier
Viewing all articles
Browse latest Browse all 1529

Here's a simple function for calculating the GCD of any 2 positive integers.

$
0
0
This can be useful component of a number of other algorithms.

Code:

Private Function GetGCD(ByVal a As Long, ByVal b As Long) As Long
Dim r As Long
Dim q As Long

' Make sure that a >= b, by XOR swapping a and b if b>a.
If a < b Then
    a = a Xor b
    b = a Xor b
    a = a Xor b
End If

' Use Euclidean algorithm to calculate GCD.
Do
    q = a \ b
    r = a Mod b
    a = b
    b = r
Loop Until r = 0

GetGCD = a
End Function


Viewing all articles
Browse latest Browse all 1529

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>