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

Some code to calculate the Greatest Common Divisor

$
0
0
This code sample calculates the GCD of numbers A and B, using the Euclidean algorithm (as described at https://www.khanacademy.org/computin...dean-algorithm).

Code:

Private Function CalculateGCD(ByVal A As Long, ByVal B As Long) As Long
Dim Remainder As Long

' If B is greater than A, then use the xor data swap technique.
If B > A Then
    B = A Xor B
    A = A Xor B
    B = A Xor B
End If

' Calculate the GCD.
Do Until B = 0
    Remainder = A Mod B
    A = B
    B = Remainder
Loop

CalculateGCD = A
End Function


And here's a small bit of code used to test the above function.
Code:

Private Sub Form_Load()
MsgBox CalculateGCD(100, 36)
End Sub

The output for this example should be 4.



Another thing that the GCD is useful for is to find if two given numbers are mutually prime. By definition, any two numbers are mutually prime if those numbers have a GCD of 1. The below code is a random mutual prime number pair generator. Its outputs are 31 bit numbers. It must be 31 bits, not 32, because all numbers larger than &h7FFFFFFF actually used as two's compliment negative numbers in VB6's data type. So I can't use the full 32 bit range. However, this works great for demonstrating the idea of mutually prime numbers.

Code:

Private Sub Form_Load()
Dim A As Long
Dim B As Long

Randomize

Do
    A = Int(Rnd * 256) * &H1& + Int(Rnd * 256) * &H100& + Int(Rnd * 256) * &H10000 + Int(Rnd * 128) * &H1000000
    B = Int(Rnd * 256) * &H1& + Int(Rnd * 256) * &H100& + Int(Rnd * 256) * &H10000 + Int(Rnd * 128) * &H1000000
Loop Until CalculateGCD(A, B) = 1

MsgBox "A=" & CStr(A) & " and B=" & CStr(B)
End Sub


Viewing all articles
Browse latest Browse all 1449

Trending Articles



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