the analysis Toolpak provides GCD and LCM and are great but some
colleagues in other schools when using my educational XL files cant
install the Toolpak due to network restrictions
is there a way of doing away with the need for the Toolpak to do GCD and
LCM and writing some formualae within a few Excel cells (not a VBA
macro) to find the GCD and LCM dynamically as my data set of 2, 3 and 4
numbers is randomly changing
a challenging math problem!!
You've got me intrigued. After a bit of googling, one of the first
links <
http://www.geocities.com/SiliconValley/Garage/3323/aat/a_eucl.html>
provided the following insights. Let me know if the code works.
Apparently, good old Euclid came up with this theorem:
GCD(A,B)=GCD(B,A Mod B)
which in VBA looks like:
===== Start: EuclidGCD =====
Function EuclidGCD(a As Variant, b As Variant) As Long
' Source: Knuth D. E., Seminumerical Algorithms, vol. 2 of The Art of Computer Programming
' Addison-Wesley, 1973
' as found at <
http://www.geocities.com/SiliconValley/Garage/3323/aat/a_eucl.html>
If b = 0 Then
EuclidGCD = a
Else
EuclidGCD = EuclidGCD(b, a Mod b)
End If
End Function
===== End: EuclidGCD =====
As we have to deal with more than just a pair of values, I wrote
this wrapper:
===== Start: myGCD =====
Function myGCD(a As Variant) As Long
' Wrapper to pass elements of an array to EuclidGCD [
[email protected]]
Dim i As Long
Dim x As Long
x = EuclidGCD(a(LBound(a)), a(LBound(a) + 1))
For i = LBound(a) + 1 To UBound(a)
x = EuclidGCD(a(i), x)
Next i
myGCD = x
End Function
===== End: myGCD =====
Tho test it, I used this:
===== Start: testmyGCD =====
Sub testmyGCD() ' Test the function myGCD()
Dim a() As Variant
a = Array(n1, n2, ...) ' You populate it
Debug.Print myGCD(a)
End Sub
===== Start: testmyGCD =====
As for LCM, Euclid observed that:
LCM(A,B)=A * B / GCD(A, B)
which in VBA looks like:
===== Start: EuclidLCM =====
Function EuclidLCM(a As Variant, b As Variant) As Long
' Source: Knuth D. E., Seminumerical Algorithms, vol. 2 of The Art of Computer Programming
' Addison-Wesley, 1973
' as found at <
http://www.geocities.com/SiliconValley/Garage/3323/aat/a_eucl.html>
EuclidLCM = a * b / EuclidGCD(a, b)
End Function
===== End: EuclidLCM =====
Again, to accommodate more than a single pair, I wrote this wrapper:
===== Start: myLCM =====
Function myLCM(a As Variant) As Long
' Wrapper to pass elements of an array to EuclidGCD() [
[email protected]]
Dim i As Long
Dim x As Long
x = EuclidLCM(a(LBound(a)), a(LBound(a) + 1))
For i = LBound(a) + 1 To UBound(a)
x = EuclidLCM(a(i), x)
Next i
myLCM = x
End Function
===== End: myLCM =====
To test this, I had:
===== Start: testmyLCM =====
Sub testmyLCM() ' Test the function myLCM()
Dim a() As Variant
a = Array(n1, n2, ...) ' You populate it
Debug.Print myLCM(a)
End Sub
===== End: testmyLCM =====
The code is only superficially tested. I know it's prone to
overflows. It does no parameter checking. Good luck.