大数加法
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
// C = A + B;
string add(const string& A, const string& B)
{
string C;
int t = 0;
for (int i = A.size()-1, j = B.size()-1; i >= 0 || j >= 0 || t > 0; i--, j--)
{
if (i >= 0) t += (A[i] - '0');
if (j >= 0) t += (B[j] - '0');
C += ((t % 10) + '0');
t /= 10;
}
reverse(C.begin(), C.end());
return C;
}
int main()
{
ios::sync_with_stdio(false);
string A, B;
cin >> A >> B;
cout << add(A, B) << endl;
return 0;
}
大数减法
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string sub(const string& A, const string& B)
{
string C;
int t = 0;
for (int i = A.size()-1, j = B.size()-1; i >= 0 || j >= 0 || t > 0; i--, j--)
{
if (i >= 0) t = (A[i] - '0') - t;
if (j >= 0) t -= (B[j] - '0');
C += ((t + 10) % 10 + '0');
if (t < 0) t = 1;
else t = 0;
}
while (C.size() > 1 && C.back() == '0') C.pop_back();
reverse(C.begin(), C.end());
return C;
}
bool cmp(const string& A, const string& B)
{
if (A.size() != B.size()) return A.size() > B.size();
for (int i = 0; i < A.size(); i++)
if (A[i] != B[i]) return A[i] > B[i];
return true;
}
int main ()
{
ios::sync_with_stdio(false);
string A, B;
cin >> A >> B;
if (cmp(A, B)) cout << sub(A, B) << endl;
else cout << "-" << sub(B, A) << endl;
return 0;
}
大数乘法(一个大数乘一个小点的数,都是正数)
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
// res = A * B
string mul(const string& A, const int b)
{
string res;
for (int i = A.size() - 1, t = 0; i >= 0 || t > 0; i--)
{
if (i >= 0) t += (A[i] - '0') * b;
res += (t % 10) + '0';
t /= 10;
}
reverse(res.begin(), res.end());
return res;
}
int main ()
{
ios::sync_with_stdio(false);
string A;
int b;
cin >> A >> b;
cout << mul(A, b) << endl;
return 0;
}
大数除法(一个大数除一个小点的数,都是正数,除不尽的话输出整数部分)
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
// res = A / b, r = A % b;
string div(const string& A, const int& b, int& r)
{
string res;
for (int i = 0; i < A.size(); i++)
{
r = r * 10 + (A[i] - '0');
res += (r / b) + '0';
r %= b;
}
while (res.size() > 1 && res.front() == '0') res = res.substr(1);
return res;
}
int main ()
{
ios::sync_with_stdio(false);
string A;
int b;
cin >> A >> b;
int r = 0;
cout << div(A, b, r) << endl;
cout << r << endl;
return 0;
}