2012年11月20日 星期二

最大公約數

利用歐基里德輾轉相除法寫一個程式。輸入兩個正整數,輸出其最大公約數。輸入數值的大小限制於3到1000之間。

輸入說明:每一列由二個數字所組成,為一組測試資料。每個數字與數字間的區隔為一個空白符號,當為0 0時表示結束。(請參照輸入範例)
輸入範例:in.txt
78 64
26 39
0 0

輸出說明:對於每組測試資料,輸出最大公約數。(請參照輸出範例)
輸出範例:out.txt
2
13

6 則留言:

  1. Dim max, min As Integer
    Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2

    Do
    Input #1, max, min
    If max = min And min = 0 Then Exit Do
    If max < min Then temp = max: max = min: min = temp
    Do
    If min = 0 Then Print #2, max: Exit Do
    temp = min
    min = max - (min * (max \ min))
    max = temp
    Loop
    Loop
    Close #2
    Close #1
    End
    End Sub

    回覆刪除
  2. Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Do
    Input #1, a, b
    If a = 0 And b = 0 Then Exit Do
    Do Until a = 0 Or b = 0
    If a > b Then
    a = a Mod b
    Else
    b = b Mod a
    End If
    Loop
    If a = 0 Then Print #2, b Else Print #2, a
    Loop
    Close
    Close
    End
    End Sub

    回覆刪除
  3. 作者已經移除這則留言。

    回覆刪除
  4. 作者已經移除這則留言。

    回覆刪除
  5. Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Do
    Input #1, x
    Input #1, y
    If x = 0 Or y = 0 Then Exit Do
    If x > y Then a = x: x = y: y = a
    For i = x To 2 Step -1
    If x Mod i = 0 And y Mod i = 0 Then Exit For
    Next
    Print #2, i
    Loop
    Close #2
    Close #1
    End
    End Sub

    回覆刪除
  6. Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Do
    Input #1, x
    Input #1, y
    If x = 0 Or y = 0 Then Exit Do
    Do
    If x = y Or y = 0 Then Exit Do
    If x > y Then a = x: x = y: y = a
    y = y Mod x
    Loop
    Print #2, x
    Loop
    Close #2
    Close #1
    End
    End Sub

    回覆刪除