2010年7月31日 星期六

2010年3月29日 星期一

大數除法

'大數除法
Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim a = "1234567890123456788999999"
        Dim b = "12345678901234567890"
        Dim q = 0
        While a.Length > b.Length Or a.Length = b.Length And a >= b
            q = q + 1
            a = bigSub(a, b)
        End While
        MsgBox(q)
        End
    End Sub
    Function bigSub(ByVal n1, ByVal n2)
        Dim a(100)
        Dim b(100)
        Dim d(100)

        Dim i1 = 0
        For i = n1.Length - 1 To 0 Step -1
            a(i1) = Val(n1.Chars(i))
            i1 = i1 + 1
        Next

        Dim i2 = 0
        For i = n2.Length - 1 To 0 Step -1
            b(i2) = Val(n2.Chars(i))
            i2 = i2 + 1
        Next

        Dim imax = IIf(i1 > i2, i1, i2)

        Dim c = 0
        For i = 0 To imax
            If a(i) - c >= b(i) Then
                d(i) = a(i) - b(i) - c
                c = 0
            Else
                d(i) = a(i) - b(i) - c + 10
                c = 1
            End If
        Next

        Dim str = ""
        For i = 0 To imax
            str = d(i) & str
        Next

        While Microsoft.VisualBasic.Left(str, 1) = "0"
            str = Microsoft.VisualBasic.Right(str, str.Length - 1)
        End While
        Return (str)
    End Function
End Class


大數乘法

'大數乘法
Public Class Form1
    '12345*45678=563894910
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim a(300)
        Dim b(300)
        Dim c(600)
        Dim aStr = "12345"
        Dim bStr = "45678"
        Dim i
        Dim ia = 0
        For i = aStr.Length - 1 To 0 Step -1
            a(ia) = aStr.Chars(i)
            ia = ia + 1
        Next
        Dim ib = 0
        For i = bStr.Length - 1 To 0 Step -1
            b(ib) = bStr.Chars(i)
            ib = ib + 1
        Next

        Dim j
        For i = 0 To 300
            For j = 0 To 300
                c(i + j) = c(i + j) + Val(a(i)) * Val(b(j))
            Next
        Next
        For i = 0 To 300 - 1
            If c(i) >= 10 Then
                c(i + 1) = c(i + 1) + c(i) \ 10
                c(i) = c(i) Mod 10
            End If
        Next

        Dim str = ""
        For i = 0 To 300
            str = c(i) & str
        Next

        While Microsoft.VisualBasic.Left(str, 1) = "0"
            str = Microsoft.VisualBasic.Right(str, str.ToString.Length - 1)
        End While
        MsgBox(str)
    End Sub
End Class