Multiple Big Number Problem

Can we store number 4 in code? Yes, we can.
Can we store number 33889194 in code? Yes, we can.
Can we store number 2938492384928349823498234982349823948 in code? Yes… but we need to have BigInt.

Adding two 100 or 200 digits number is relatively easy and we can do it on paper if our calculator cannot do it. What about multiplication? It is more time consuming and easier to make a mistake using paper and pen. Let’s extend our BigInt by multiplication to save some time.

How To Do It?

The first number will be multiplied by each digit from the second one. Then the zeros will be added to this temp result (Why to add zeros? Check the graphic below). Then temp result will be added to the final result.

Multiplication
Red zeros added the same as those in code to make an addition.

Multiplication first number by one digit. The function calculates single line for instance 7416 or 2472 (without zeros here).


struct BigInt {
    
//previous code

   
 private static func multiply(_ bigInt: BigInt, by multiplier: String) -> String {
        
let multiplicand: String = String(bigInt.value.reversed())
        
let multi: Int = Int(multiplier)!
        
var result: String = “”
        
var buffor: Int = 0         

        
for char in multiplicand {
            
let currentNumber = Int(String(char))!
            
let tempResult = buffor + (currentNumber * multi)
            buffor = tempResult /
10
            result += String(tempResult %
10)
        }

        
if buffor > 0 {
            result += String(buffor)
        }

        
return String(result.reversed())
    }
}

The static function allows to overload operator. After this, we will be able to use “*” between two instances of BigInt.

struct BigInt {
//previous code

    
static func *(lhs: BigInt, rhs: BigInt) -> BigInt {
        
let multi: String = String(rhs.value.reversed())
        
var result: BigInt = BigInt(value: “0”)
        
var extraZeros: String = “”

        
for char in multi {
            
var tempResult: String = multiply(lhs, by: String(char))
            tempResult += extraZeros
            result = result + BigInt(value: tempResult)
            extraZeros +=
“0”
        }

        
return result
   }
}

Let’s check the result.

print(\(big.value) * \(big.value) = \((big * big).value)”)
print(\(big.value) * \(big2.value) = \((big * big2).value)”)
print(\(big.value) * \(big3.value) = \((big * big3).value)”)

OUTPUT

1236 * 1236 = 1527696
1236 * 55 = 67980
1236 * 23 = 28428