2009年4月7日 星期二

求最大公因數 - 三種方法

'求最大公因數
Public Class Form1
    Dim i
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim n1 = 18
        Dim n2 = 12
        'Dim n1 = Val(InputBox("請輸入要求最大公因數的第一個數"))
        'Dim n2 = Val(InputBox("請輸入要求最大公因數的第二個數"))

        '窮舉法
        Dim gcd = 1
        For i = 2 To n1
            If n1 Mod i = 0 And n2 Mod i = 0 Then
                gcd = i
            End If
        Next
        MsgBox(n1 & "," & n2 & "的最大公因數=" & gcd)

        '輾轉相除法
        n1 = 42
        n2 = 105
        Dim n1b = n1
        Dim n2b = n2
        While n1 <> n2
            If n1 > n2 Then
                n1 = n1 - n2
            Else
                n2 = n2 - n1
            End If
        End While
        gcd = n1
        MsgBox(n1b & "," & n2b & "的最大公因數=" & gcd)

        '遞迴法
        n1 = 64
        n2 = 48
        gcd = gcd1(n1, n2)
        MsgBox(n1 & "," & n2 & "的最大公因數=" & gcd)

    End Sub

    Function gcd1(ByVal x1, ByVal x2)
        If x1 = x2 Then
            gcd1 = x1
        Else
            If x1 > x2 Then
                gcd1 = gcd1(x1 - x2, x2)
            Else
                gcd1 = gcd1(x1, x2 - x1)
            End If
        End If
    End Function
End Class

沒有留言:

張貼留言