You're welcome.
Reverse iterators make things a little easier. |
I think you could use the forward iterator but then you must start at v.end()-1.
v.end() is invalid, so your for loop line 28 may not work.
You would also want to include v.begin(), which your for loop would stop at.
I think the only way you will get a carry > 8 (9*9 = 81 is max 1-digit case) is if mult >=10 (ie greater than the base you are representing in).
In this case, I think the result will still be OK except for the last carry.
I tried modifying multiply to allow for a multi-digit final carry, changing:
1 2 3 4
|
if( carry > 0 )// push_front the carry
{
v.insert( v.begin(), carry );
}
|
to:
1 2 3 4 5
|
while( carry > 0 )// push_front the carry
{
v.insert( v.begin(), carry%10 );
carry /= 10;
}
|
I tested this against finding 2^1000 = (32)^200 with:
1 2 3 4 5
|
vector<int> numbers;
numbers.push_back(1);
for( int i=1; i<= 200; ++i)
multiply(numbers, 32);
|
I still get the correct answer.
EDIT: max carry=9, not 8 for 1-digit case. I forgot that carry would be summed so max case is 9*9 + 9 = 90
Testing theory re. use of forward iterator in multiply:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
void multiply2(vector<int>& v, const int mult)
{
vector<int>::iterator it = v.end()-1;
int product= (*it)*mult;// 1st term explicitly
int carry = product/10;
*it = product%10;
while( it != v.begin() )
{
--it;// so v.begin will be included
product = (*it)*mult + carry;
carry = product/10;
*it = product%10;
}
while( carry > 0 )// push_front the carry
{
v.insert( v.begin(), carry%10 );
carry /= 10;
}
}
|
This works too.
@ne555 and cire. I would store the digits in the opposite order too and use push_back for the carries, but bickels had it setup as low digit last. I was just trying to make it work that way.