C++實現大數乘法演算法代碼_C 語言

來源:互聯網
上載者:User

C++實現大數乘法演算法代碼

複製代碼 代碼如下:

//大數乘法演算法
#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 << "]為:" << x1 << endl;
        char carry = '0';
        for (int j = strlen(n2)-1; j >= 0; j--)
        {
            int x2 = n2[j]-'0';
            //cout << "n2["<< j << "]為:" << x2 << endl;
            //cout << "當前位未改變前值為: " << n[count] << endl;
            int sum = x1*x2 + (carry-'0') + n[count]-'0';
            //cout << "sum is " << sum << endl;
            n[count++] = (sum % 10)+'0';
            carry = (sum / 10)+'0';
            //cout << "當前位的值為: " << n[count-1] << endl;
            //cout << "carry的值為:" << carry << endl;
        }
        if (carry != '0')
        {
            n[count] = carry;
            count = flag;
            //cout << "當前位的值為: " << n[count] << endl;
        }
        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;
}

以上就是本文所述的全部內容了,希望大家能夠喜歡。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.