How to find ratio between 2 numbers. Example: Ratio of 12 & 8 is 3:2
Printable View
How to find ratio between 2 numbers. Example: Ratio of 12 & 8 is 3:2
Here you go, it simply divides both numbers by 1,2.. up to half the value of the first number (the maximum possible divider). if both numbers can be divided exactly by the loop value then they are stored.. easy!
;)VB Code:
val_1 = 12 val_2 = 8 For i = 1 To (val_1 \ 2) If (val_1 / i) = (val_1 \ i) And _ (val_2 / i) = (val_2 \ i) Then min_1 = (val_1 / i) min_2 = (val_2 / i) End If Next i MsgBox CStr(min_1) & ":" & CStr(min_2)
Why only up to half the first number?Quote:
up to half the value of the first number (the maximum possible divider).
because anything higher cannot possibly return a whole number,Quote:
Why only up to half the first number?
BUT you have reminded me of a minor omission, you should also allow for dividing by the number itself! do'h!
eg: 8 / 8 = 1 (gimme a few seconds to update the code!)
ideally you should only check up to half of the lowest value rather than just the first (and there are other ways of reducing the workload), but unless you are working on huge numbers the speed isn't that important.
better version:
VB Code:
val_1 = 15 val_2 = 120 If val_1 < val_2 Then min_val = val_1 Else min_val = val_2 End If If (val_1 / min_val) = (val_1 \ min_val) And _ (val_2 / min_val) = (val_2 \ min_val) Then min_1 = (val_1 / min_val) min_2 = (val_2 / min_val) Else min_1 = val_1 min_2 = val_2 For i = (min_val \ 2) To 1 Step -1 If (val_1 / i) = (val_1 \ i) And _ (val_2 / i) = (val_2 \ i) Then min_1 = (val_1 / i) min_2 = (val_2 / i) Exit For End If Next i End If MsgBox CStr(min_1) & ":" & CStr(min_2)
Thank you
Ah your right Si, thanks!