int最大是2147483647,long long最大是9223372036854775807
故而超过18位的数需要用字符串来运算。
两个大整数相加
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s1, s2, sum="";
cin >> s1 >> s2;
int n1 = s1.size()-1, n2 = s2.size()-1, a = 0;
while (n1 >= 0 || n2 >= 0 || a == 1)
{
if (n1 >= 0)
{
a += s1[n1] - '0';
n1--;
}
if (n2 >= 0)
{
a += s2[n2] - '0';
n2--;
}
sum = to_string(a % 10) + sum;
a /= 10;
}
cout << sum << endl;
system("pause");
return 0;
}
两个大整数相减
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s1, s2, res="";
cin >> s1 >> s2;
int n1 = s1.size() - 1, n2 = s2.size() - 1, a = 0;
if (n1 < n2) //s1为较大的数
{
string t = s2;
s2 = s1;
s1 = t;
}
int len = n1 - n2; //s2补全0
string s3(len, '0');
s2 = s3 + s2;
for (int i = n1; i >= 0; i--)
{
a = (s1[i] - '0') - (s2[i] - '0') - a;
if (a < 0)
{
res = to_string(a + 10) + res;
a = 1;
}
else
{
res = to_string(a) + res;
a = 0;
}
}
if (res[0] == '0')
{
cout << res.substr(1) << endl;
}
else
{
cout << res << endl;
}
system("pause");
return 0;
}
两个大整数相乘
#include<iostream>
#include<string>
using namespace std;
string BigNumMultiply(string str1, string str2)
{
int size1 = str1.size(), size2 = str2.size();
string str(size1 + size2, '0'); //str保存乘法结果
for (int i = size2 - 1; i >= 0; --i)
{
int mulflag = 0, addflag = 0; //mulflag是乘法的进位,addflag是加法的进位
for (int j = size1 - 1; j >= 0; --j)
{
int temp1 = (str2[i] - '0')*(str1[j] - '0') + mulflag; //逐位相乘
mulflag = temp1 / 10;
temp1 = temp1 % 10;
int temp2 = str[i + j + 1] - '0' + temp1 + addflag; //第i+j+1位加上相乘结果
str[i + j + 1] = temp2 % 10 + '0';
addflag = temp2 / 10;
}
str[i] += mulflag + addflag; //第i位加上进位
}
if (str[0] == '0') //首位是0则去掉
str = str.substr(1);
return str;
}
int main()
{
string str1, str2;
cin >> str1 >> str2;
cout << BigNumMultiply(str1, str2) << endl;
system("pause");
return 0;
}
两个大整数相除
#include<iostream>
#include<string>
using namespace std;
string BigNumMultiply(string str1, string str2)
{
int size1 = str1.size(), size2 = str2.size();
string str(size1 + size2, '0');
for (int i = size2 - 1; i >= 0; --i)
{
int mulflag = 0, addflag = 0;
for (int j = size1 - 1; j >= 0; --j)
{
int temp1 = (str2[i] - '0')*(str1[j] - '0') + mulflag;
mulflag = temp1 / 10;
temp1 = temp1 % 10;
int temp2 = str[i + j + 1] - '0' + temp1 + addflag;
str[i + j + 1] = temp2 % 10 + 48;
addflag = temp2 / 10;
}
str[i] += mulflag + addflag;
}
if (str[0] == '0')
str = str.substr(1, str.size());
return str;
}
int main()
{
string str1, str2;
while (cin >> str1 >> str2)
{
cout << str1 << "*" << str2 << "=" << endl;
cout << BigNumMultiply(str1, str2) << endl;
}
system("pause");
return 0;
}