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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…