How to multiply two long numbers in C++

3 Answers

0 votes
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

/*
  Multiply Two Long Numbers
  ------------------------------------
  Implements manual big‑integer multiplication
  using decimal strings.
*/

std::string longmulti(const std::string& A, const std::string& B) {
    std::string a = A;
    std::string b = B;

    // Trim leading spaces
    a.erase(0, a.find_first_not_of(' '));
    b.erase(0, b.find_first_not_of(' '));

    // Handle sign
    bool sign = false;
    if (!a.empty() && a[0] == '-') { sign = !sign; a.erase(0, 1); }
    if (!b.empty() && b[0] == '-') { sign = !sign; b.erase(0, 1); }

    // Remove leading zeros
    a.erase(0, a.find_first_not_of('0'));
    b.erase(0, b.find_first_not_of('0'));
    if (a.empty()) a = "0";
    if (b.empty()) b = "0";

    // If either is zero
    if (a == "0" || b == "0")
        return "0";

    int la = a.size();
    int lb = b.size();
    std::string result(la + lb, '0');

    // Multiply from right to left
    for (int i = la - 1; i >= 0; --i) {
        if (!std::isdigit(a[i])) continue;
        int carry = 0;

        for (int j = lb - 1; j >= 0; --j) {
            if (!std::isdigit(b[j])) continue;

            int pos = i + j + 1;
            int n = (a[i] - '0') * (b[j] - '0')
                    + (result[pos] - '0') + carry;

            result[pos] = char('0' + (n % 10));
            carry = n / 10;
        }

        result[i] = char(result[i] + carry);
    }

    // Remove leading zero if present
    if (result[0] == '0')
        result.erase(0, 1);

    // Add sign
    if (sign)
        result.insert(result.begin(), '-');

    return result;
}

int main() {
    std::string r = longmulti(
        " 18361891827367132321",
        "-18361891827367132321"
    );

    std::cout << r << '\n';
}


/*
run:

-337159071479931885857929667075122847041

*/

 



answered 4 days ago by avibootz
edited 4 days ago by avibootz
0 votes
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
#include <algorithm>
#include <cctype>

/*
  Multiply Two Long Numbers
  ------------------------------------
  Implements manual big‑integer multiplication
  using decimal strings.
*/

std::string longmulti(std::string_view a, std::string_view b) {
    // Trim leading spaces
    auto trim = [](std::string_view s) {
        auto pos = s.find_first_not_of(' ');
        return pos == std::string_view::npos ? std::string_view{} : s.substr(pos);
    };
    a = trim(a);
    b = trim(b);

    // Handle sign
    bool negative = false;
    if (!a.empty() && a.front() == '-') { negative = !negative; a.remove_prefix(1); }
    if (!b.empty() && b.front() == '-') { negative = !negative; b.remove_prefix(1); }

    // Remove leading zeros
    auto strip_zeros = [](std::string_view s) {
        auto pos = s.find_first_not_of('0');
        return pos == std::string_view::npos ? std::string_view{"0"} : s.substr(pos);
    };
    a = strip_zeros(a);
    b = strip_zeros(b);

    if (a == "0" || b == "0")
        return "0";

    int la = a.size();
    int lb = b.size();

    std::vector<int> digits(la + lb, 0);

    // Multiply digits
    for (int i = la - 1; i >= 0; --i) {
        if (!std::isdigit(a[i])) continue;
        for (int j = lb - 1; j >= 0; --j) {
            if (!std::isdigit(b[j])) continue;

            int ai = a[i] - '0';
            int bj = b[j] - '0';
            int pos = i + j + 1;

            int sum = digits[pos] + ai * bj;
            digits[pos] = sum % 10;
            digits[pos - 1] += sum / 10;
        }
    }

    // Convert vector<int> → string
    std::string result;
    result.reserve(la + lb);

    // Skip leading zero
    size_t start = (digits[0] == 0 ? 1 : 0);
    for (size_t i = start; i < digits.size(); ++i)
        result.push_back(char('0' + digits[i]));

    if (negative)
        result.insert(result.begin(), '-');

    return result;
}

int main() {
    std::string r = longmulti(
        " 18361891827367132321",
        "-18361891827367132321"
    );

    std::cout << r << '\n';
}



/*
run:

-337159071479931885857929667075122847041

*/

 



answered 4 days ago by avibootz
edited 4 days ago by avibootz
0 votes
#include <iostream>
#include <string>
#include <vector>

// Function to multiply two absolute string numbers
std::string multiplyAbsolute(std::string num1, std::string num2) {
    int n1 = num1.size();
    int n2 = num2.size();
    if (n1 == 0 || n2 == 0) return "0";

    // Result can have at most n1 + n2 digits
    std::vector<int> result(n1 + n2, 0);

    // Shift positions from right to left
    for (int i = n1 - 1; i >= 0; i--) {
        for (int j = n2 - 1; j >= 0; j--) {
            int mul = (num1[i] - '0') * (num2[j] - '0');
            // Sum with the existing value at this position
            int sum = mul + result[i + j + 1];

            // Update the current position and the carry
            result[i + j + 1] = sum % 10;
            result[i + j] += sum / 10;
        }
    }

    // Convert vector back to string, skipping leading zeros
    std::string resultStr = "";
    bool leadingZero = true;
    for (int num : result) {
        if (num == 0 && leadingZero) continue;
        leadingZero = false;
        resultStr += std::to_string(num);
    }

    return resultStr.empty() ? "0" : resultStr;
}

// Main function that manages signs and calls the multiplier
std::string multiplyBigInt(std::string num1, std::string num2) {
    if (num1 == "0" || num2 == "0") return "0";

    // Determine the sign of the result
    bool isNegative = false;
    if (num1[0] == '-') {
        isNegative = !isNegative;
        num1 = num1.substr(1); // Remove '-'
    }
    if (num2[0] == '-') {
        isNegative = !isNegative;
        num2 = num2.substr(1); // Remove '-'
    }

    std::string result = multiplyAbsolute(num1, num2);
    
    return isNegative ? "-" + result : result;
}

int main() {
    std::string num1 = "18361891827367132321";
    std::string num2 = "-18361891827367132321";

    std::string product = multiplyBigInt(num1, num2);

    std::cout << "Num 1:   " << num1 << std::endl;
    std::cout << "Num 2:   " << num2 << std::endl;
    std::cout << "Product: " << product << std::endl;
}


/*
run:

Num 1:   18361891827367132321
Num 2:   -18361891827367132321
Product: -337159071479931885857929667075122847041

*/

 



answered 4 days ago by avibootz
...