2012年7月31日 星期二

聯集

讀入兩個正整數a以及b,請書出介於a及b之間(包含a、b)2、3、5倍數的聯集大小。
例如1及10之堅,是2倍數集合為{2、4、6、8、10};是3倍數為{3、6、9};是5倍數集合為{5、10},上述三個集合的聯集為{2、3、4、5、6、8、9、10},故聯集大小為8。
輸入規範:輸入檔案中可能包含了好幾列的測試資料,每一列有兩個整數(即a及b)。a=0、b=0代表輸入結束。
輸出規範:對每一列輸入,輸出聯集的大小(請參考輸出範例)。

輸入範例:
1  10
10  20
0  0
輸出範例:
8
7

3 則留言:

  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
    Do While Not EOF(1)
    Input #1, a, b
    ans = 0
    If a <> 0 And b <> 0 Then
    For i = a To b
    If i Mod 2 = 0 Or i Mod 3 = 0 Or i Mod 5 = 0 Then ans = ans + 1
    Next
    Else
    End
    End If
    Print #2, ans
    Loop
    Close
    Close
    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 While Not EOF(1)
    ans = 0
    Input #1, x, y
    If x = 0 And y = 0 Then Exit Do
    For i = x To y
    If i Mod 2 = 0 Or i Mod 3 = 0 Or i Mod 5 = 0 Then ans = ans + 1
    Next i
    Print #2, ans
    Loop
    Close #2
    Close #1
    End
    End Sub

    回覆刪除
  3. Dim tw(), th(), fi() 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, x, y
    If x = 0 And y = 0 Then Exit Do
    r = 1: s = 1: t = 1: g = 1: ans = 0
    For i = Val(x) To Val(y)
    ReDim tw(r), th(s), fi(t)
    If i Mod 2 = 0 Then tw(r) = i: r = r + 1
    If i Mod 3 = 0 And i Mod 2 <> 0 Then th(s) = i: s = s + 1
    If i Mod 5 = 0 And i Mod 2 <> 0 And i Mod 3 <> 0 Then fi(t) = i: t = t + 1
    Next i
    Print #2, UBound(tw) - 1 + UBound(th) - 1 + UBound(fi) - 1
    Loop
    Close #2
    Close #1
    End
    End Sub

    回覆刪除