2012年7月12日 星期四

質因數分解

從輸入檔in.txt中,讀入1正的長整數,請將此數分解成質因數的乘積,輸出到out4.txt

輸入範例: in.txt
248417
輸出範例: out.txt
248417 = 13 * 97 * 197

2 則留言:

  1. Private Sub Form_Load()
    Me.Hide
    Dim x As Long
    Dim a As Boolean
    Dim b(20) As Long
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Input #1, x
    a = True
    n = x
    c = 0
    a = True
    For i = 2 To (x \ 2)
    Do
    If x Mod i = 0 Then
    For j = 2 To (i \ 2)
    If j Mod i = 0 Then a = False: Exit For
    Next
    If a = True Then d = i
    End If
    If n = 1 Then Exit Do
    If d = 0 Then Exit Do
    If (n Mod d) <> 0 Then Exit Do
    c = c + 1
    n = n / d
    b(c) = d
    Loop Until n = 1
    Next
    Print #2, x & "=";
    For i = 1 To c
    Print #2, b(i);
    If i < c Then Print #2, "*";
    Next
    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
    Dim n As Long, t As Boolean, x As String
    Dim a()
    Input #1, n
    ReDim a(n)
    c = 1
    For i = 2 To n - 1
    If n Mod i = 0 Then
    t = False
    For j = 2 To i - 1
    If i Mod j = 0 Then t = True
    Next j
    If t = False Then
    a(c) = i
    c = c + 1
    End If
    End If
    Next i
    x = n & "="
    For k = 1 To c - 1
    x = x & a(k)
    If k <> c - 1 Then
    x = x & "*"
    End If
    Next k
    Print #2, x
    Close #2
    Close #1
    End
    End Sub

    回覆刪除