We have a question for university to program a basic calculator but it would work with arbitrary integers. I have managed to get over addition and subtraction, but I do not really see how can I multiply 2 numbers when both are arbitrarily long. Currently using c language and I have been using pointers as character arrays. Any help would be very welcome...
void sum(char*a, char*b)
{
//initializing values
int c,d,i;
int carry=0;
char *r;
// counting the digits
c=strlen(a);
d=strlen(b);
// checking which array is longer
if (c>=d)
{
// if first array is longer we allocate enough memory for the result
r=(char*)malloc((c+1)*sizeof(char));
// incrementing backwards so we skip reversing the digits
for (i=0; i<=d; ++i)
{
// mod 10 to extract only the last digit of the sum
// that becomes our new digit
*(r+c-i)=(*(a+c-i)+*(b+d-i)+carry)%10;
carry=(*(a+c-i)+*(b+d-i))/10;
}
// copying the rest of the digits
for (i=d+1; i<=c; ++i)
*(r+c-i)=*(a+c-i);
}
//case when the other number has more digits
else
{
r=(char*)malloc((d+1)*sizeof(char));
for (i=0; i<=c; ++i)
{
*(r+d-i)=(*(a+c-i)+*(b+d-i)+carry)%10;
carry=(*(a+c-i)+*(b+d-i))/10;
}
for (i=c+1; i<=d; ++i)
*(r+d-i)=*(b+d-i);
}
// printing the result
printf("The result is \n %s \n", r);
}
This is my code for addition so maybe that can give more insight into the problem, and how I am approaching it.