Greatest common divisor: Difference between revisions
→{{header|VBA}}: more efficient method
(→{{header|VBA}}: more efficient method) |
|||
Line 4,464:
=={{header|VBA}}==
Dim t As Long
Do While v
t = u
u = v
v = t Mod v
Loop
gcd = u
End Function</lang>
This function uses repeated subtractions. Simple but not very efficient.
<lang VBA>Public Function GCD(a As Long, b As Long) As Long
▲Public Function GCD(a As Long, b As Long) As Long
While a <> b
If a > b Then a = a - b Else b = b - a
Wend
GCD = a
End Function</lang>{{out}}
Example:
<pre>print GCD(1280, 240)▼
▲print GCD(1280, 240)
80
print GCD(3475689, 23566319)
Line 4,485 ⟶ 4,488:
b=234736437
print GCD((a),(b))
3 </pre>
A note on the last example: using brackets forces a and b to be evaluated before GCD is called. Not doing this will cause a compile error because a and b are not the same type as in the function declaration (they are Variant, not Long). Alternatively you can use the conversion function CLng as in print GCD(CLng(a),CLng(b))
|