Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

c++ - fast multiplying two arrays with n digits in c

I tried to write the multiplication code for the huge numbers. The problem is slow. I could not execute in a short time. In this example, the execution time is about a 7 seconds. I want it in one second or less. Is there a suggestion on the code or any library that help me in my problem

string multiply(string num1, string num2) 
{ 
    int len1 = num1.size(); 
    int len2 = num2.size(); 
    vector<int> result(len1 + len2, 0);  
    int i_n1 = 0;  
    int i_n2 = 0;  
    for (int i=len1-1; i>=0; i--) 
    { 
        int carry = 0; 
        int n1 = num1[i];
        i_n2 = 0;           
        for (int j=len2-1; j>=0; j--) 
        { 
            int n2 = num2[j] ; 
            int sum = n1*n2 + result[i_n1 + i_n2] + carry; 
            carry = sum/10; 
            result[i_n1 + i_n2] = sum % 10;  
            i_n2++; 
        } 
  
        if (carry > 0) 
            result[i_n1 + i_n2] += carry; 
        i_n1++; 
    }
    int i = result.size() - 1; 
    while (i>=0 && result[i] == 0) 
    i--; 
    if (i == -1) 
    return "0"; 
    string s = ""; 
      
    while (i >= 0) 
        s += std::to_string(result[i--]);   
    return s; 
}
main()
{
    string str1 ="";
    string str2 ="";
    for(int i=0;i<50000;i++)
    {
     str1+=to_string ((rand()%10));
     str2+=to_string ((rand()%10));
    }
  clock_t t_star=clock();
  multiply(str1, str2);
  std::cout<<(double)((double)clock()-(double)t_star)/(double)CLOCKS_PER_SEC<<std::endl;
  system("pause");
}
question from:https://stackoverflow.com/questions/66050256/fast-multiplying-two-arrays-with-n-digits-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...