I didn't do this on purpose, but if you try the test case for, say 9999*9999, you will see that I didn't apply the correction that is necessary for product digits that were greater than 9 (that is, the carry into the next higher bit. I referred to this in a previous message.Quote:
Originally Posted by Dave Evans
Here's the complete example:
Regards,Code:#include <stdio.h>
#include <stdlib.h>
void product(int *n, int *m, int size);
#define SIZE 4
int main()
{
int i;
int a[SIZE] = {9, 9, 9, 9};
int b[SIZE] = {9, 9, 9, 9};
printf("a: ");
for (i = 0; i < SIZE; i++) {
printf("%d ", a[i]);
}
printf("\n");
printf("b: ");
for (i = 0; i < SIZE; i++) {
printf("%d ", b[i]);
}
printf("\n");
product(a, b, SIZE); /* calculate and print the product */
return 0;
}
void product(int *n, int *m, int size)
{
int i, j, t;
int val;
int *temp;/* will hold the product then disappear */
temp = malloc(2*size * sizeof(int));
if (!temp) {
fprintf(stderr, "Can't allocate storage for temp in product()\n");
return;
}
for(t = 0; t < size; t++) {
temp[t] = 0;
}
for(i = 0; i < size; i++) {
for (j=0; j < size; j++) {
val = n[i] * m[j]; /* partial product */
temp[i+j] += val % 10; /* partial sum this digit */
temp[i+j+1] += val / 10; /* carry into next digit */
}
}
/*
* here is the correction for digits that were greater than 9
*/
for (i = 0; i < 2*size-1; i++) {
temp[i+1] += temp[i]/10;
temp[i] %= 10;
}
/*
now print the results (remember least significant is first
*/
printf("temp: ");
for (i = 0; i < 2*size; i++) {
printf("%d ", temp[i]);
}
printf("\n");
free(temp);
}
Dave