C++ realizes the algorithm of multiplying large Numbers

  • 2020-06-19 11:18:20
  • OfStack

Since Numbers cannot be stored in an integer variable, it is natural to think of a string as a string of Numbers. Then follow the rules of multiplication, multiply each bit of one multiplier by another, and then add all the intermediate results in the correct place to get the final result. If the multipliers are A and B, the digit of A is m, and the digit of B is n, the result of the product is m+ ES8en-1 bit (the highest digit has no carry) or m+n bit (the highest digit has carry). Therefore, an m+n secondary can be allocated to store the final result. To save space, all intermediate results are accumulated directly on the auxiliary storage of m+n.

C++ realizes the multiplication code of large Numbers as follows:


#include<iostream>                               
#include<string>
using namespace std;
 
 string BigNumMultiply(string str1,string str2)
 {
 int size1=str1.size(),size2=str2.size();
 string str(size1+size2,'0');
 for(int i=size2-1;i>=0;--i)
 {
 int mulflag=0,addflag=0;
 for(int j=size1-1;j>=0;--j)
 {
 int temp1=(str2[i]-'0')*(str1[j]-'0')+mulflag;
 mulflag=temp1/10;
 temp1=temp1%10;
 int temp2=str[i+j+1]-'0'+temp1+addflag;
 str[i+j+1]=temp2%10+48;
 addflag=temp2/10;
 }
 str[i]+=mulflag+addflag;
 }
 if(str[0]=='0')
 str=str.substr(1,str.size());
 return str;
 }
 
 int main()
 {
 string str1,str2;
 while(cin>>str1>>str2)
 {
 cout<<str1<<"*"<<str2<<"="<<endl;
 cout<<BigNumMultiply(str1,str2)<<endl;
 }
 return 0;
}

Related articles: