2011年3月24日 星期四

輾轉相除法

輸入兩數,求最大公因數、最小公倍數。

限定使用輾轉相除法


輸入:
91
34

輸出:
1
3094

5 則留言:

  1. Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Input #1, N1
    Input #1, N2
    SANS = Divi((N1), (N2))
    BANS = (N1 * N2) / SANS
    Print #2, "最大公因數:" & SANS
    Print #2, "最小公倍數:" & BANS
    End
    End Sub
    Function Divi(a, b)
    Do While a <> b
    If a > b Then a = a - b Else b = b - a
    Loop
    Divi = a
    End Function

    回覆刪除
  2. Dim Mm, Nn
    Private Sub Form_Load()
    'Me.Hide
    Open App.Path & "\out.txt" For Output As #2
    Open App.Path & "\in.txt" For Input As #1
    Input #1, Mm, Nn
    Print #2, Ea(Mm, Nn)
    Print #2, ((Mm * Nn) / Ea(Mm, Nn))
    Close #1
    Close #2
    'End
    End Sub
    Function Ea(ByVal a1, ByVal b1)
    Do While a1 <> b1
    Print a1, b1
    Do While a1 > b1: a1 = a1 - b1: Loop
    Call chn(a1, b1)
    Loop
    Ea = a1
    End Function
    Sub chn(a2, b2)
    t2 = a2
    a2 = b2
    b2 = t2
    End Sub

    輸入
    44
    66
    輸出
    22
    132

    回覆刪除
  3. arro,緣尉好,
    這題雖然是簡單的題目,不過,用來練習函數副程式的呼叫,還要分別是call by value, call by reference,你們練習的很好,看得出進步,我很高興。要持續這樣子的加油哦。

    回覆刪除
  4. Dim N1 As Long
    Dim N2 As Long
    Dim ans As Long
    Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Input #1, N1, N2

    ans = N((N1), (N2))

    Print #2, "最大公因數" & ans
    Print #2, "最小公倍數" & (N1 * N2) / ans

    Close #2
    Close #1



    End
    End Sub

    Function N(A, B)
    Do
    If A > B Then
    A = A - B
    Else
    B = B - A
    End If
    Loop Until A = B
    N = A
    End Function

    回覆刪除