2012年11月5日 星期一

簡易大數加法


求兩筆數字N的和。 (N為正整數,長度不限)



輸入:

9999999999999999999999999999999999999999999999999999999999999999999999999999
1000


輸出:

10000000000000000000000000000000000000000000000000000000000000000000000000999

2 則留言:

  1. Dim add1, add2, overr, ori, ans As String
    Dim times As Integer

    Private Sub Form_Load()
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Line Input #1, add1
    Line Input #1, add2

    Do
    If Len(add1) < Len(add2) Then add1 = "0" & add1
    If Len(add2) < Len(add1) Then add2 = "0" & add2
    Loop Until Len(add1) = Len(add2)

    For i = 1 To Len(add1)
    ori = Val((Val(Right(add1, 1)) + Val(Right(add2, 1)) + Val(overr)) Mod 10)
    overr = Val((Val(Right(add1, 1)) + Val(Right(add2, 1)) + Val(overr)) \ 10)
    ans = ori & ans
    add1 = Mid(add1, 1, Len(add1) - 1)
    add2 = Mid(add2, 1, Len(add2) - 1)
    Next
    ans = overr & ans
    Print #2, ans
    Close #2
    Close #1

    回覆刪除
  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
    Line Input #1, a
    Line Input #1, b
    x = Len(a)
    y = Len(b)
    Do Until x = y
    If x > y Then
    b = "0" & b
    y = Len(b)
    Else
    a = "0" & a
    x = Len(a)
    End If
    Loop
    e = 0
    For i = x To 1 Step -1
    q = Val(Mid(a, i, 1))
    w = Val(Mid(b, i, 1))
    y = q + w + e
    If y >= 10 Then
    e = 1
    z = y - 10 & z
    Else
    e = 0
    z = y & z
    End If
    Next
    If e = 1 Then z = "1" & z
    Print #2, z
    Close #2
    Close #1
    End
    End Sub

    回覆刪除