Multiplying two integer arrays

Mar 27, 2017 at 2:43pm
Hi! So I have a class called BigInt which stores exceedingly large integers in the form of a char array of digits. For example BigInt b1("123456789") would yield b1 = {'1','2','3',...'9'}. I was trying to incorporate basic arithmetic and as such was overloading their operators. I managed to get + and - mostly working but I am stuck on multiplication.

Here's what I have so far

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
  	BigInt BigInt::operator *= (const BigInt &rhs){
		int size = m_digitArraySize + rhs.getSize();
		int* C = new int[size];
	    int s = size-1;
	    
	    for(int j= rhs.getSize() - 1; j >= 0; j--){
	        int carry = 0;
	        int shift = s;
	        for(int i = m_digitArraySize - 1; i >= 0; i--){
	            int m = getDigit(i) * rhs.getDigit(j);
	            int sum = m + C[shift] + carry;
	            int num = sum % 10;
	            int c = sum/10;
	            C[shift] = num;
	            carry = c;
	            shift--;
	        }
	        C[shift]= C[shift] + carry;            
	        s--;            
	    }
	    reallocateArray(size);
	    // for(int i = 0; i < size < ++i){
	    // 	m_digitArray[i] = '0' + C[i];
	    // }
            // This is for debugging only, I realize I'm not returning the actual BigInt
	    for (int i = 0; i < size; ++i)
	    {
	    	cout << C[i];
	    }
		return *this;
	}

	// Overload the * operator for BigInt * BigInt operations
	BigInt operator * (const BigInt &lhs, const BigInt &rhs){
		return BigInt(lhs) *= rhs;
	}

	// Overload the * operator for BigInt * int operations
	BigInt operator * (const BigInt &lhs, int num){
		return BigInt(lhs) *= num;
	}

	// Overload the * operator for int * BigInt operations
	BigInt operator * (int num, const BigInt &rhs){
		return BigInt(rhs) *= num;
	}
Last edited on Mar 27, 2017 at 2:44pm
Mar 27, 2017 at 10:00pm
it works just like it would if you did it by hand.

digit * digit = more digits with "carry".

that is...

9*9 = 1 carry the 8.

this is terribly inefficient though.
you can do the above using 64 bits or more at a time using the built-in multiplier.

lets say you had 5 digit numbers supported on the CPU... then

10000
*
11
=
110000
or
10000 carry the 1 ... you can use the same principles ... see? Its not exact because you can carry more than 1 digit, but the principles work fine, you can carry 100 same as carrying a 1...

you look like you are on the right track for the 1 digit at a time approach ... if you wanted to explain what its doing wrong? It looks close, but its easier to look at the example of the bug alongside the code.
Last edited on Mar 27, 2017 at 10:03pm
Topic archived. No new replies allowed.