2012年11月5日 星期一

第一次儲備選手選拔試卷第二題

判斷質數:從指定目錄"in.txt"讀取一數字,判斷是否為質數輸出至指定目錄"out.txt"。
("是質數","不是質數")

輸入範例:197

輸出範例:是質數

3 則留言:

  1. Dim num As Integer
    Private Sub Form_Load()
    Open App.Path & "\in.txt" For Input As #1
    Input #1, num
    Close

    ok = 0

    For i = 1 To num
    If num Mod i = 0 Then ok = ok + 1
    Next

    Open App.Path & "\out.txt" For Output As #1
    If ok > 2 Then Print #1, "不是質數"
    If ok = 2 Then Print #1, "是質數"
    Close

    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

    Dim t As Boolean

    Input #1, x
    t = True
    For i = 2 To x \ 2
    If x Mod i = 0 Then t = False
    Next
    If t = True Then Print #2, "是質數" Else Print #2, "不是質數"

    Close
    Close
    End
    End Sub

    回覆刪除
  3. Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Dim n As Integer
    Dim a As Boolean
    Do While Not EOF(1)
    Input #1, n
    If n < 2 Then a = False: Print #2, "不是質數": End
    a = True
    For i = 2 To n \ 2
    If n Mod i = 0 Then a = False: Exit For
    Next
    If a = True Then
    Print #2, "是質數"
    Else
    Print #2, "不是質數"
    End If
    Loop
    Close
    Close
    End
    End Sub

    回覆刪除