-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBIGNUM.cpp
83 lines (80 loc) · 1.85 KB
/
BIGNUM.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// 48 trong bài mang ý nghĩa: '0' là 48 trong mã ASCII
#include<iostream>
#include<string>
using namespace std;
string add(string a, string b)
{
string res="";
while(a.length() < b.length()) a="0"+a; // chèn các số 0 vào chuỗi a
while(b.length() < a.length()) b="0"+b;
int carry=0;
for(int i=a.length()-1;i>=0;i--)
{
int tmp=a[i]-48 + b[i]-48 + carry; // vì đã chèn số 0 rồi, nên thoải mái +
carry=tmp/10; // lay phan nguyen
tmp=tmp%10;
res=(char)(tmp+48)+res;
}
if(carry>0) res="1"+res;
return res;
}
string sub(string a, string b)
{
string res="";
while(a.length() < b.length()) a="0"+a;
while(b.length() < a.length()) b="0"+b;
bool neg=false;
if(a<b)
{
swap(a,b);
neg=true;
}
int borrow=0;
for(int i=a.length()-1; i>=0;i--)
{
int tmp=a[i]-b[i]-borrow;
if(tmp<0)
{
tmp+=10;
borrow=1;
}
else borrow=0;
res=(char)(tmp%10 + 48) + res;
}
while(res.length()>1 && res[0]=='0') res.erase(0,1); // xoa cac so 0 phia truoc
if(neg) res="-"+res;
return res;
}
string mul(string a, string b)
{
string res="";
int n=a.length();
int m=b.length();
int len=n+m-1;
int carry=0;
for(int i=len;i>=0;i--)
{
int tmp=0;
for(int j=n-1;j>=0;j--)
if(i-j<=m && i-j>=1)
{
int a1=a[j]-48;
int b1=b[i-j-1]-48;
tmp+=a1*b1;
}
tmp+=carry;
carry=tmp/10;
res=(char)(tmp%10 + 48)+res;
}
while(res.length()>1 && res[0]=='0') res.erase(0,1);
return res;
}
int main()
{
//freopen("in.txt","r",stdin);
string a, b;
cin>>a>>b;
cout<<add(a,b)<<endl;
cout<<sub(a,b)<<endl;
cout<<mul(a,b);
}