实验二
求解大整数乘法问题
1. 实验内容
计算两个大整数的乘积
2. 实验目的
学会用分治法求解计算问题
3. 实验题目
本实验要求实现以下功能:
(1) 从键盘中输入两个大整数,两个大整数必须要用字符串数组存储。
(2) 给出这两个大整数的乘积。
vs2022,c++
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
/*
X*Y = a00 00+b00+c00+d
*/
string addhq(string num1, string num2) {
//从后往前加,end 1,end 2分别为num1,num2的最后一个字符
int end1 = num1.size() - 1;
int end2 = num2.size() - 1;
int value1 = 0;
int value2 = 0;
int next = 0;//进位
int add = 0;
string addret;
while (end1 >= 0 || end2 >= 0) {//二者完成遍历
add = 0;
if (end1 >= 0) {//1
value1 = num1[end1--] - '0';//把ASCLL码转换成数值
}
else {
value1 = 0;
}
if (end2 >= 0) {//2
value2 = num2[end2--] - '0';
}
else {
value2 = 0;
}
add = value1 + value2 + next;
if (add > 9) {
next = 1;
add -= 10;
}
else {
next = 0;
}
addret += add + '0';
}
if (next == 1) {//next等于1有进位
addret += '1';
}
//逆
reverse(addret.begin(), addret.end());
return addret;
}
string xxy(string x, string y) {//x*y
cout << "计算" << x << "*" << y << endl;
int long1 = x.size();
int long2 = y.size();
int xx = 0, yy = 0, i = 0;
if (long1 == 1 && long2 == 1) {//二者只有一位,进行运算
string xy;
stringstream strx;
strx << x; strx >> xx;
stringstream stry;
stry << y; stry >> yy;
stringstream strxy;
int a = xx * yy;
strxy << a; strxy >> xy;
return xy;
}
if (long1 > 1 && long2 == 1) {//n*1
string a = x.substr(0, x.size() / 2);
string b = x.substr(x.size() / 2, x.size() - 1);
string H = xxy(b, y);
string Q = xxy(a, y);
for (i = 1; i <= x.size() - x.size() / 2; i++) {
Q = Q + '0';
}
return addhq(H, Q);
}
if (long1 == 1 && long2 > 1) {
return xxy(y, x);
}
if (long1 > 1 && long2 > 1) {//n*n
string a = x.substr(0, x.size() / 2);
string b = x.substr(x.size() / 2, x.size() - 1);
string c = y.substr(0, y.size() / 2);
string d = y.substr(y.size() / 2, y.size() - 1);
string ac = xxy(a, c), ad = xxy(a, d), bc = xxy(b, c), bd = xxy(b, d);
for (i = 1; i <= (x.size() - x.size() / 2) + (y.size() - y.size() / 2); i++) {
ac = ac + '0';
}
for (i = 1; i <= y.size() - y.size() / 2; i++) {
bc = bc + '0';
}
for (i = 1; i <= x.size() - x.size() / 2; i++) {
ad = ad + '0';
}
return addhq(ac, addhq(ad, addhq(bc, bd)));
}
return "q";
}
int main()
{
string x, y;
cout << "输入x:";
cin >> x;
cout << endl << "输入y:";
cin >> y;
system("cls");
cout << "x:" << x << endl << "y:" << y << endl;
int qwe = 1;//符号记录
if (x[0] == '-') {
qwe = -1 * qwe;
x = x.substr(1, x.size() - 1);
}
if (y[0] == '-') {
qwe = -1 * qwe;
y = y.substr(1, y.size() - 1);
}
string xy = xxy(x, y);
if (qwe == -1) {
xy = '-' + xy;
}
cout << "xy:" << xy << endl;
return 0;
}