Big number subtraction

Bigint operator-(const Bigint &n1, const Bigint &n2) {
Bigint result;
int carry = 0;

for (int i = 255; i >= 0; i--) {
if (n1.arr[i] - n2.arr[i] - carry) {
result.arr[i] = n1.arr[i] - n2.arr[i] % 10 + 10;
if (result.arr[i] >= 10) {
result.arr[i] = n1.arr[i] - 1;
}
carry = 1;
} else {
result.arr[i] = n1.arr[i] - n2.arr[i] - carry;
carry = 0;
}
}
return result;
}
//end code
when I do 300-12, it prints result 298 instead of 288. I could not figure it out why?
did you mean
result[i] = (n1[i] - n2[i] -carry) % 10 + 10;
this is still not totally right, though. I think your carry logic is messed up...
this works for 300-12 and 312-12 both. maybe it will help. It is still not complete: 25-50 won't work, because it 'borrows' when there is nothing to take. you need a way to handle that, and it also sort of absolute values the answer, so you need to retain the overall result negative sign somehow as well. The easiest way to solve this if n2 > n1, swap them and change the sign. so 25-50 becomes 50-25 * -1 = -25... you may also need to allow for a result bigger than the inputs... -9 - 9 is -18. The best way to do bignum type work is to have the least significant digit in [0], backwards of what you are doing. ever better is to use a computer base, not base 10. 31 bit numbers, for example, can be squared into 64 bit numbers... and you can leverage the computer's ability to do the pieces in 64 bit, and just manually carry the pieces around to the next chunk.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int n1[] = {3,2,4};
int n2[] = {0,1,2};
int result[4]{};
int main()
{
	int carry = 0;
	int tmp;
	for (int i = 3; i >= 0; i--) 
	{
		tmp = n1[i]-n2[i]-carry;
		result[i] = (tmp +10)%10;
		carry = (int)( tmp < 0) ;
	}
	cout << result[0] << result[1] << result[2] << result[3]<< endl;
}
Last edited on
Topic archived. No new replies allowed.