大數乘法——逐位與移位算法

在題目中,總會出現要求用很大很大的數來進行運算,這時候就涉及大數運算,這次首先介紹一下大數乘法的處理。代碼經過優化,非常簡便

逐位相乘處理進位法

乘積是逐位相乘,也就是aibj ,結果加入到積c的第i+j位,最後處理進位即可

舉例:

A=13,B=19
a=(3,1),b=(9,1)
c=(3 9,3 1+1 9,1 1)=(27,12,1)=(7,14,1)=(7,4,2)
C=247

因此,大題思路是:

  • 轉換並反轉,字符串轉換爲數字並將字序反轉;
  • 逐位相乘,並處理進位,結果存放在result[i+j]中;
  • 消除多餘的0;
  • 轉換並反轉,將計算結果轉換爲字符串並反轉。

我將代碼優化,儘可能減少代碼的書寫

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

using namespace std;

void multply(string &a, string &b)
{
    string result(a.size()+b.size(),'0');//初始化結果數組
    unsigned int c = 0;
    for(unsigned int i = 0; i < a.size(); i++)
    {
        unsigned int j;
        for(j = 0; j < b.size(); j++)
        {
            c +=  (result[i+j] - '0') + (a[i] - '0')*(b[j] - '0');
            result[i+j] = (c % 10) + '0';
            c /= 10;
        }
        while(c)
        {
            result[i+j++] += (c % 10);
            c /= 10;
        }
    }
    for(unsigned int i = result.size() - 1; i >= 0; i--)//去掉高位0
    {
        if(result[i] != '0')
        {
            break;
        }
        else
        {
            result.erase(result.begin() + i,result.end());//截斷後面全0
        }
    }
    //cout<<result<<endl;
    reverse(result.begin(),result.end());
    cout<<result<<endl;
}

main()
{
    string a,b;
    cin>>a>>b;
    reverse(a.begin(),a.end());
    reverse(b.begin(),b.end());
    multply(a,b);
}

運行結果:

這裏寫圖片描述

這裏寫圖片描述

移位進位法

舉例:
這裏寫圖片描述

因此,大體思路是:

  • 轉換並反轉,字符串轉換爲數字並將字序反轉;
  • 移位相乘,並處理進位,結果存放在result[i]中;
  • 消除多餘的0;
  • 轉換並反轉,將計算結果轉換爲字符串並反轉。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

void multply(string a, string b)
{
    string result(a.size()+b.size(),'0');//初始化結果數組
    unsigned int c = 0, tmp_i = 0, tmp_j = 0;
    for(unsigned int i = 0; i!=a.size(); i++, tmp_j++)
    {
        tmp_i = tmp_j;  //在每次計算時,結果存儲的位需要增加
        unsigned int j;
        for(j = 0; j < b.size(); j++)
        {
            c += (result[tmp_i] - '0') + (a[i] - '0')*(b[j] - '0');
            result[tmp_i++] = (c % 10) + '0';
            c /= 10;
        }
        while(c)//處理最後進位
        {
            result[tmp_i++] = (c % 10) + '0';
            c /= 10;
        }
    }
    for(unsigned int i = result.size() - 1; i >= 0; i--)
    {
        if(result[i] != '0')
        {
            break;
        }
        else
        {
            result.erase(result.begin() + i,result.end());//截斷後面全0
        }
    }
    //cout<<result<<endl;
    reverse(result.begin(),result.end());
    cout<<result<<endl;
}

int main()
{
    string a,b;
    cin>>a>>b;
    reverse(a.begin(),a.end());
    reverse(b.begin(),b.end());
    multply(a,b);
    return 0;
}

運行結果

這裏寫圖片描述
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章