I am making a calculator that accepts large number (represented as strings) and performs basic math functions on them. So far I have Add and Multiply figured out.
Here is addition
And MultiplyCode:Private Function Add(ByVal Number1 As String, ByVal Number2 As String) As String Dim num1, num2, r, total As New Integer Dim sum As String = "" ' Make the numbers the same length, padding zeroes were necessary. If Number1.Length > Number2.Length Then Number2 = Number2.PadLeft(Number1.Length, Chr(48)) Else Number1 = Number1.PadLeft(Number2.Length, Chr(48)) End If ' This loop adds each column of numbers together, along with the remainder from the previous column. For i As Integer = Number1.Length - 1 To 0 Step -1 num1 = Val(Number1(i)) num2 = Val(Number2(i)) total = num1 + num2 + r r = 0 ' Reset the remainder Do While total > 9 total -= 10 r += 1 Loop sum = total & sum ' Adds the new column answer in front of the previous one. Next If r <> 0 Then ' If there is a remainder, put it on the front. Return r & sum Else Return sum End If End Function
How would I do subtract and divide?Code:Private Function Multiply(ByVal Number1 As String, ByVal Number2 As String) As String Dim num1(Number1.Length - 1), num2(Number2.Length - 1), r, temp As Integer Dim total(num1.Count - 1) As String ' Fill the arrays with the digits of each number For a As Integer = Number1.Length - 1 To 0 Step -1 num1(a) = Val(Number1(a)) num2(a) = Val(Number2(a)) Next ' Multiply each lower digit by each upper digit For b As Integer = num2.Count - 1 To 0 Step -1 For c As Integer = num1.Count - 1 To 0 Step -1 temp = num1(c) * num2(b) + r ' Multiply the two number together along with any remainder. r = 0 ' Reset the remainder to 0 Do While temp > 9 And Not c = 0 ' If the number is greater than 9 then we need to get the remainders. temp -= 10 r += 1 Loop total(b) = temp & total(b) ' Store the answer Next Next ' Pad following zeroes For d As Integer = 2 To total.Count For f As Integer = 2 To d total(total.Count - d) = total(total.Count - d) & "0" Next Next ' Add the totals together Dim sum As String = "" For e As Integer = total.Count - 1 To 0 Step -1 sum = Add(sum, total(e)) Next ' Trim leading zeroes and commas TrimZero(sum) ' Add the remainder to the front of the sum, if it exists. ' Return the number If r <> 0 Then Return r & sum Else Return sum End If End Function
I saw something like this in the code bank but the examples there were from VB6(?) and were hugely inefficient (compared his Add and Multiply examples to mine, his having way more code and loops.)




Reply With Quote