I'm trying to write my own function from scratch to add large numbers. This function takes the input of an unsigned long long array, with each number being 10 didgets long (the reason for the long long signed is becouse I might expand it) and adds it to the output array (same format). It seems for some reason the output array remains null. Would anyone point out any problems? Thanks.
#include <stdio.h>
void add(long long unsigned int input[], int isize,
long long unsigned output[], int osize );
int main() {
long long unsigned int output[4] = {0};
long long unsigned int input[2][3] =
{{9999999999LL, 9999999999LL, 9999999999LL},
{9999999999LL, 9999999999LL, 9999999999LL}};
add(input[0], 3, output, 10);
add(input[1], 3, output, 10);
printf("%llu%llu%llu%llu\n", output[0], output[1], output[2], output[3]);
return 0;
}
void add(long long unsigned int input[], int isize,
long long unsigned output[], int osize) {
/* This function will add input to output and store it in output. Here's a
picture of how a 5 didget one would work:
| 1 | 1 | |<-carry
|-----------------------|
| 00000 | 99999 | 99999 |<-in
| 00000 | 99999 | 99999 |<-out
|-----------------------|
| 1 | 99999 | 99998 |<-temp
After every addition, the last 5 didgets of temp become the current 'out',
and the rest of the didgets become the next 'carry'. This function is a 10
didget one. */
long long unsigned int carry = 0, temp = 0;
int count = 0;
while(count != osize) { /* While there is output left */
if(isize <= count) { /* if there is more input */
temp = input[count]; /* load up temp (input + output + carry) */
temp += output[count];
temp += carry;
if(temp >= 10000000000LL) { /* If there will be a carry */
output[count] = temp % 10000000000LL; /* output = last 10 didgets */
carry = temp / 10000000000LL; /* carry = the rest of the didgets */
}
else { /* If there is going to be no carry */
output[count] = temp;
carry = 0;
}
}
else { /* if there is no more input, but more output */
temp = output[count]; /* load everthing into temp (output + carry) */
temp += carry;
if(temp >= 10000000000LL) { /* If there is going to be a carry */
output[count] = temp % 10000000000LL; /* output = last 10 didgets */
carry = temp / 10000000000LL; /* carry = the rest of the didgets */
}
else { /* If there is no carry */
output[count] = temp;
return; /* no need to go further */
}
}
count++; /* Can't forget this ;-) */
}
}