I'm trying to finish a hw where one of the requirement is a method that takes in two linked lists, multiply them, and return the result in another list. This is my implementation so far:
The code works fine if I call the addition method. However, whenever I call the multiplication method, it only spits back at me the last digit of the right result. After some testing and debugging, I think the problem is that when I call the add method in my multiplication method, only the last digits of my two lists are passed, not the entire list. How do I fix this?
what is multiply doing again?
5*3 is
5+5+5.
multiply should just be
product = 0;
for(i = 0; i < number of times; i++) //number of times is 3
product = product+number //number is 5 here, of course
so you need to loop, calling add over and over.
your multiply is doing something weird. I can't make much sense of it.
just make product a list, and call add N times. Its that simple (assuming add works right).
Remember you have to convert N to a normal int if it is a list, or find a way to loop that many times if it a big-int (more than 64 bits or whatever). If its more than 64 bits, you are going to be waiting on your answer for a while.
it is woefully inefficient to multiply via adds this way: there are probably slick algorithms to do this with less work. But crude and simple is fine to start with.
First you have to split the logic to add/mutli numbers and the container (linked list) to store digits. Then use std::vector than a self implementation of a linked list.
The rest was fun to code :)
Your carry calculations are too complex. carry = value / 10;
Use -- to decrement a variable. e.g., length--;
The code works fine if I call the addition method.
Are you sure? Try printing x.length() inside operator<<. You'll find that it's wrong and that this is one reason that mult() fails.
Don't modify length inside add(). You actually don't need to use it, just check whether temporary1 and temporary2 are non-null.
There are at least SEVEN different places where you add a digit to a NaturalNumber. There should be only ONE - inside a function. Then you'd only have to adjust the length in one place.
You'll probably find that your code doesn't work well with zero. I prefer to represent 0 as an empty list, rather than a 1-digit value. Add special code in operator<< to handle this.
You leak memory everywhere. For now, I'd just live with it since fixing it is a bunch of work.
Pulling together all the advice above and putting it in one file (just for my convenience):