Search code examples
c++powbigint

Multiplying big numbers


The problem is to multiply big numbers.

I am using a base of 10^9, and get problems when the numbers get to tenth of that. In the example below, I use a much smaller base for simplicity.

#include <iostream>
#include <vector>

using namespace std;

typedef vector<long long> largen;

const int base = 1000;

largen  multiply(largen a, largen b) {
    largen c(a.size() + b.size());
    for (size_t i = 0; i<a.size(); ++i)
        for (size_t j = 0, carry = 0; j < (int)b.size() || carry; ++j) {
            long long cur = c[i + j] + a[i] * 1ll * (j < (int)b.size() ? b[j] : 0) + carry;
            carry = (long long)(cur / base);
            c[i + j] = (long long)(cur % base);
        }
    while (c.size() > 1 && c.back() == 0)
        c.pop_back();
    return c;
}

int main() {
    largen a = {100};
    largen result = multiply(a, a);
    for (int i = result.size() - 1; i >= 0; i--) {
        cout << result[i];
    }
    return 0;
}

Expected answer "10000", actual answer "100"


Solution

  • So this is why we demand a Minimal, Complete, Verifiable Example. Once we have that, we can see that the problem is nothing to do with the multiplication. In fact the problem is in the lines:

        for (int i = result.size() - 1; i >= 0; i--) {
            cout << result[i];
        }
    

    If you change that to:

        for (int i = result.size() - 1; i >= 0; i--) {
            cout << result[i] << '#'
        }
    

    The output changes from the (incorrect) "100", to a much more interesting "10#0#". The second digit is being displayed as a single digit zero, rather than three zeros. Use setw and padding to make sure that all but the first digit are zero filled.