How can I multiply really big numbers c++

前端 未结 9 1671
梦谈多话
梦谈多话 2021-01-18 10:09

I have the following code

      int i, a, z;
i = 2343243443;
a = 5464354324324324;
z = i * a;
cout << z << endl;

When these are

9条回答
  •  醉话见心
    2021-01-18 11:06

    I would like to elaborate on, and clarify Shravan Kumar's Answer using a full-fledged code. The code starts with a long integers a & b, which are multiplied using array, converted to a string and then back into the long int.

    #include 
    #include 
    #include
    
    using namespace std;
    
    int main()
    {
    //Numbers to be multiplied
    long a=111,b=100;
    
    //Convert them to strings (or character array)
    string arr1 = to_string(a), arr2 = to_string(b); 
    
    //Reverse them
    reverse(arr1.begin(), arr1.end());
    reverse(arr2.begin(), arr2.end());
    
    //Getting size for final result, just to avoid dynamic size
    int ans_size = arr1.size() + arr2.size();
    
    //Declaring array to store final result
    int ans[ans_size]={0};
    
    //Multiplying 
    //In a reverse manner, just to avoid reversing strings explicitly 
    for(int i=0; i int)
            int p = (int)(arr1[i]) - '0';
            int q = (int)(arr2[j]) - '0';
    
            //Excerpt from Shravan's answer above
            ans[i+j]+=p*q;
            ans[i+j+1]=ans[i+j+1]+ans[i+j]/10;
            ans[i+j]%=10;
        }
    }
    
    //Declare array to store string form of final answer
    string s="";
    
    for(auto i=0;i

提交回复
热议问题