C++ to achieve large number multiplication algorithm code

  • 2020-04-02 03:01:57
  • OfStack

C++ to achieve large number multiplication algorithm code


//Large number multiplication algorithm
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int main()
{
    string num1,num2;
    cin >> num1 >> num2;
    //cout << num1.size() << " " << num2.size() << endl;
    const char* n1;
    const char* n2;
    if (num1.size() < num2.size())
    {
        n1 = num2.c_str();
        n2 = num1.c_str();
    }
    else
    {
        n1 = num1.c_str();
        n2 = num2.c_str();
    }
    char* n = new char[strlen(n1)+strlen(n2)+1];
    for (unsigned int i = 0; i < strlen(n1)+strlen(n2); i++)
        n[i] = '0';
    n[strlen(n1)+strlen(n2)]='0';
    //cout << strlen(n) << endl;
    int count = 0,flag = 0;
    for (int i = strlen(n1)-1; i >= 0; i--)
    {
        flag++;
        int x1 = n1[i]-'0';
        //Cout <<"N1 ["<<I <<"] is: "<<The x1 <<Endl; < br / >         char carry = '0';
        for (int j = strlen(n2)-1; j >= 0; j--)
        {
            int x2 = n2[j]-'0';
            //Cout <<"N2 ["<<j <<"] is: "<<X2 <<Endl; < br / >             //Cout <<"The previous value of the current bit unchanged is:" <<N [count] <<Endl; < br / >             int sum = x1*x2 + (carry-'0') + n[count]-'0';
            //cout << "sum is " << sum << endl;
            n[count++] = (sum % 10)+'0';
            carry = (sum / 10)+'0';
            //Cout <<"The current bit value is:" <<N [count - 1] <<Endl; < br / >             //Cout <<The value of "carry is: "<<Carry <<Endl; < br / >         }
        if (carry != '0')
        {
            n[count] = carry;
            count = flag;
            //Cout <<"The current bit value is:" <<N [count] <<Endl; < br / >         }
        else
            count = flag;
    }
    for (int i = strlen(n)-1; i >= 0; i--)
    {
        if ((i == strlen(n)-1)&&(n[i] == '0'))
            continue;
        cout << n[i];
    }
    cout << endl;
    delete[]n;
    system("pause");
    return 0;
}

That's all for this article, I hope you enjoy it.


Related articles: