简体   繁体   中英

Multiplying two large integers stored as integer vectors

I have to multiply two integers which are stored as vectors.To store the final result i am using

std::vector<std::vector<int>> result

where i store the partial result rows and the last row would store the final result.I have calculated the partial result rows and now have to add them.I already have a large integer addition function.To align the partial result rows what i do is append zeroes in all partial result rows as required(1 zero appended to 2nd partial result row,2 0's appended to 3rd partial result row etc).Then i add all partial result rows and store the result in another row.Now i remove the appended zeroes in similar manner.

void putzeroesatend(std::vector<std::vector<int>> &something)
{
    std::vector<std::vector<int>>::iterator i;      
    int k=0;
    for(i=something.begin();i!=something.end();i++,k++)
    {
        for(int p=1;p<=k;p++)
           (*i).push_back(0);
    }
}
void removezeroesatend(std::vector<std::vector<int>> &something)
{
     std::vector<std::vector<int>>::iterator i;
     int k=0;
     for(i=something.begin();i!=something.end()-1;i++,k++)
     {
         for(int p=1;p<=k;p++)
        (*i).pop_back();
     }
 }

then in my multiply function after calculating the partial results, i do the following

putzeroesatend(result);
std::vector<int> newrow;
result.push_back(newrow);

for(p=result.begin();p!=result.end()-1;p++)
{
    result[result.size()-1]=add(result[result.size()-1],*p);
}

removezeroesatend(result);

This is working but what could be a better solution to add the partial results without having to append the zeroes and then remove it.

As @Mark Ransom recommended, you could create an add function that takes unaligned operands. But I think it might be better to encapsulate your large int representation in a class that includes an exponent and then write operands for these objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM