-
Hi there,
I generate two random numbers and I'm looking for a way to find the lowest common denominator between them.
Say my numbers generated are 6 and 10. Well my code says 'if 6 Mod 10 =0, then lowest denominator is 6, or if 10 Mod 6 =0, then lowest denominator is 10....if neither of these is the case, then multiply 6 by 10 and that's the lowest denominator, i.e: 60. But we all know 30 is actually the lowest denominator.
This is what I use at present, but it's not good enough.
'2 command buttons
'two pictureboxes
Dim random1 As Integer
Dim random2 As Integer
Dim lowestdenom As Integer
Private Sub Command1_Click()
Randomize
random1 = Int(Rnd * 20) + 1
random2 = Int(Rnd * 20) + 1
Picture1.Cls
Picture1.Print random1 & " " & random2
End Sub
Private Sub Command2_Click()
If random1 Mod random2 = 0 Then
lowestdenom = random1
End If
If random2 Mod random1 = 0 Then
lowestdenom = random2
End If
If random1 Mod random2 <> 0 And random2 Mod random1 Then
lowestdenom = (random1 * random2)
End If
Picture2.Cls
Picture2.Print lowestdenom
End Sub
Any help would be appreciated!
-
There might be a better formula for doing this but here is a function that will return the lowest common denominator of two values past to the function.
Code:
Public Function LowestDenom(ByVal i1 As Integer, ByVal i2 As Integer) As Long
Dim iTemp As Integer
If i2 > i1 Then
'make sure i1 is the highest number
iTemp = i1
i1 = i2
i2 = iTemp
End If
iTemp = 1
Do While (i1 * iTemp) Mod i2 <> 0
iTemp = iTemp + 1
Loop
LowestDenom = i1 * iTemp
End Function
You can use the function in the following manner:
Code:
Private Sub Command1_Click()
Dim random1 As Integer
Dim random2 As Integer
random1 = Int(Rnd * 20) + 1
random2 = Int(Rnd * 20) + 1
MsgBox "Lowest common denominator of the values " _
& random1 & " and " & random2 & " is " & _
LowestDenom(random1, random2)
End Sub
Good luck!
-
Thanks Joacim! Works great.
-
You can use this too:
Code:
Public Function LowestDenom(ByVal i1 As Integer, ByVal i2 As Integer) As Long
Dim k As Long
For k = IIf(i1 < i2, i2, i1) To i1 * i2
If k Mod i1 = 0 And k Mod i2 = 0 Then
LowestDenom = k
Exit For
End If
Next k
End Function
in the same way as Joacim's function.