Originally Posted by
neandrake
ok, so I tried rewriting the whole function with no luck still. This is so aggrevating. I've tried following through the code and I can't see why it doesn't work. This was my original function, which makes more sense to me, but it still doesn't work!
At the top of this thread you said that you didn't want anyone to furnish you with detailed code, so up until now I have tried to keep things general. I will now get a little more specific, so if you don't to see some code, stop reading now.
Here's an example in C, using your program as a starting point:
(Yes, I know this is the C++ board, but the algorithm applies to C and C++ users alike --- so sue me.)
Now, just because it works for a few examples doesn't mean that you should accept it as perfect. Test, test, test (but remember that you can't prove a program is correct by testing --- make sure it does exactly what you want.)
Change SIZE to anything you want, and use any numbers you want (Obviously it only works for non-negative integers.)
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] = {7, 0, 0, 0};
int b[SIZE] = {9, 9, 0, 0};
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 */
}
}
printf("temp: ");
for (i = 0; i < 2*size; i++) {
printf("%d ", temp[i]);
}
printf("\n");
free(temp);
}
[edit]
Disclaimer: This is a test case; I have tried to make it correct, but I make no claims as to optimality, efficiency, elegance or anything else. If it helps,, I say, "Good." If not, I say, "Good day."
[/edit]
Regards,
Dave