表紙へ

3.最大公約数

 

以下のGCF関数を使うと最大公約数を得ることができる。

例:GCF(15, 24, 60) = 3

Public Function GCF(ParamArray Values() As Variant) As Long

    Dim Temp As Long
    Dim X As Long
    Dim Y As Long
    Dim K As Long
    Dim PrevResult As Long

    PrevResult = Abs(Values(0))

    For K = 0 To UBound(Values()) - 1

        X = PrevResult
        Y = Abs(Values(K + 1))

        Temp = X Mod Y

        Do While Temp > 0
            X = Y
            Y = Temp
            Temp = X Mod Y
        Loop

        PrevResult = Y

    Next K

    GCF = Y

End Function