2011年4月8日 星期五

大數費氏函數

輸入一正整數N,並用大數加法的方式輸出第N項費氏函數。


第一項為 1
第二項為 1
第三項為 2


輸入:
70

輸出:
190392490709135

4 則留言:

  1. Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Input #1, n
    Close #1

    Dim a As String, b As String

    a = 1: b = 0
    For i = 1 To n - 1
    ans = Bplus(a, b): b = a: a = ans
    Next

    Open App.Path & "\out.txt" For Output As #2
    Print #2, ans
    Close #2
    End
    End Sub




    Function Bplus(N1 As String, N2 As String)
    Dim NS1 As Integer, NS2 As Integer, Tmp As Integer, Plus As String, FAns As String

    Do Until Len(N1) = Len(N2)
    If Len(N1) > Len(N2) Then
    N2 = "0" & N2
    Else
    N1 = "0" & N1
    End If
    Loop


    For i = Len(N1) To 0 Step -1

    If i = 0 Then
    FAns = Tmp & FAns
    Else
    NS1 = Mid(N1, i, 1)
    NS2 = Mid(N2, i, 1)
    Plus = NS1 + NS2
    FAns = ((Plus + Tmp) Mod 10) & FAns
    Tmp = (Plus + Tmp) \ 10
    End If

    Next

    If Left(FAns, 1) = "0" Then FAns = Right(FAns, Len(FAns) - 1)

    Bplus = FAns

    End Function

    回覆刪除
  2. arro好,
    我喜歡這個大數的費氏函數,做得好。

    回覆刪除
  3. Private Sub Form_Load()
    Me.Hide
    Dim d(1000) As String
    Open App.Path & "\out.txt" For Output As #2
    Open App.Path & "\in.txt" For Input As #1

    Input #1, n

    d(0) = 0
    d(1) = 1
    For i = 2 To n
    d(i) = p(d(i - 1), d(i - 2))
    Next
    Print #2, d(n)
    Close #1
    Close #2
    End
    End Sub
    Function p(m, n)
    Lenm = Len(m)
    Lenn = Len(n)
    Do Until i > Lenm And i > Lenn
    If Lenm > i Then x = Val(Mid(m, Lenm - i, 1)) Else x = 0
    If Lenn > i Then y = Val(Mid(n, Lenn - i, 1)) Else y = 0
    z = x + y + c
    c = z \ 10
    a = (z Mod 10) & a
    i = i + 1
    If i > Lenm And i > Lenn And (z Mod 10 = 0) Then a = Right(a, Len(a) - 1)
    Loop
    p = a
    End Function
    ----------------
    in.txt
    70
    out.txt
    190392490709135

    回覆刪除
  4. 緣尉好,
    這題ok,但是,你不是在試最大值嗎? 有試出來嗎? 而且是可以驗証的哦,不可以給了一個天花亂墜的答案,只有天知道的。

    回覆刪除