Yes, it's yet another thread about implementing three basic operations (addition, subtraction and multiplication) on abnormally large numbers (> 100 digits).
I've stored each digit inside an array of int
s, as the following piece of code illustrates
while((ch = getchar()) != EOL)
a[len_a++] = ch - CHR;
Now, when it comes to adding them, I add the (len_number - k)th digits of both numbers, compute their reminder and their quotient, and store the reminder on the kth place of the sum
array. The following piece of code works nicely for, say, 132 and 32, but when I try adding 1248 and 2, the result 1950, instead of 1350. I think I'm doing some illegal work on the arrays (at some point, I have something like b[1 - 3]
), but I've been struggling for a lot of time and I still can't figure things out, so any help would be highly appreciated.
for(i = 1; i <= len_a || i <= len_b; ++i) {
aux = (a[len_a - i] + b[len_b - i] + qtt);
rem = aux % 10;
sum[i - 1] = rem;
++len_sum;
qtt = aux / 10;
}
And here's the big picture
#include <stdio.h>
#define NR_DIG 100
#define EOL '\n'
#define CHR '0'
int main(void) {
unsigned short a[NR_DIG], b[NR_DIG], sum[NR_DIG + 1];
int ch, len_a = 0, len_b = 0, len_sum = 0, rem, qtt = 0, i, aux;
printf("a: ");
while((ch = getchar()) != EOL)
a[len_a++] = ch - CHR; /* ch - CHR = input - its character part */
printf("b: ");
while((ch = getchar()) != EOL)
b[len_b++] = ch - CHR;
for(i = 1; i <= len_a || i <= len_b; ++i) {
aux = (a[len_a - i] + b[len_b - i] + qtt);
rem = aux % 10;
sum[i - 1] = rem;
++len_sum;
qtt = aux / 10;
}
printf("a + b: ");
for(i = len_sum - 1; i >= 0; --i)
printf("%hu", sum[i]);
printf("\n");
return 0;
}