C++实现大数乘法算法代码

时间:2021-05-20

C++实现大数乘法算法代码

复制代码 代码如下:
//大数乘法算法
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int main()
{
string num1,num2;
cin >> num1 >> num2;
//cout << num1.size() << " " << num2.size() << endl;
const char* n1;
const char* n2;
if (num1.size() < num2.size())
{
n1 = num2.c_str();
n2 = num1.c_str();
}
else
{
n1 = num1.c_str();
n2 = num2.c_str();
}
char* n = new char[strlen(n1)+strlen(n2)+1];
for (unsigned int i = 0; i < strlen(n1)+strlen(n2); i++)
n[i] = '0';
n[strlen(n1)+strlen(n2)]='\0';
//cout << strlen(n) << endl;
int count = 0,flag = 0;
for (int i = strlen(n1)-1; i >= 0; i--)
{
flag++;
int x1 = n1[i]-'0';
//cout << "n1["<< i << "]为:" << x1 << endl;
char carry = '0';
for (int j = strlen(n2)-1; j >= 0; j--)
{
int x2 = n2[j]-'0';
//cout << "n2["<< j << "]为:" << x2 << endl;
//cout << "当前位未改变前值为: " << n[count] << endl;
int sum = x1*x2 + (carry-'0') + n[count]-'0';
//cout << "sum is " << sum << endl;
n[count++] = (sum % 10)+'0';
carry = (sum / 10)+'0';
//cout << "当前位的值为: " << n[count-1] << endl;
//cout << "carry的值为:" << carry << endl;
}
if (carry != '0')
{
n[count] = carry;
count = flag;
//cout << "当前位的值为: " << n[count] << endl;
}
else
count = flag;
}
for (int i = strlen(n)-1; i >= 0; i--)
{
if ((i == strlen(n)-1)&&(n[i] == '0'))
continue;
cout << n[i];
}
cout << endl;
delete[]n;
system("pause");
return 0;
}

以上就是本文所述的全部内容了,希望大家能够喜欢。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章