-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubtraction.cpp
More file actions
97 lines (83 loc) · 2.32 KB
/
Subtraction.cpp
File metadata and controls
97 lines (83 loc) · 2.32 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#ifndef SUBTRACTION
#define SUBTRACTION
#include "Number.hpp"
Number* Sub(Number* A, Number* B) {
// IMPLICIT ASSUMPTION: A>B
// if any one of the number is negative, call sub
// adjust exponents
// add the numbers
// restore exponents
// return
Number* A_Copy;
Number* B_Copy;
Number* Ans;
bool sign_flag = false;
// after this step, magnitude of A_Copy is bigger
if(Number::compare(A, B) >= 0) {
A_Copy = new Number(A);
B_Copy = new Number(B);
sign_flag = false;
}
else {
A_Copy = new Number(B);
B_Copy = new Number(A);
sign_flag = true;
}
// adjust exponents
int restoringExp = 0;
// 0 if A_Copy has smaller exp, 1 if B_Copy has smaller exp
int biggerExpNo = 0;
if(A_Copy->exponent >= B_Copy->exponent) {
Number::padNumbers(A_Copy, B_Copy);
biggerExpNo = 0;
}
else {
Number::padNumbers(B_Copy, A_Copy);
biggerExpNo = 1;
}
int k = A_Copy->digits.size();
int l = B_Copy->digits.size();
int base = A_Copy->base;
int carry = 0;
vector<int> c_dig(k, 0);
// addition (both will have the same size)
for(int i = 0;i < k;i++) {
int temp = A_Copy->digits[i] - B_Copy->digits[i] + carry;
carry = Number::QuoRem(temp, base).first;
c_dig[i] = Number::QuoRem(temp, base).second;
}
if(carry==-1) {
cout << "Error";
}
int c_exp = (biggerExpNo == 0 ? A_Copy->exponent : B_Copy->exponent);
free(A_Copy);
free(B_Copy);
Ans = new Number(c_dig, base, c_exp, sign_flag);
Ans->removeZeroes(true);
return Ans;
}
// int main()
// {
// vector<int> a = {0,2};
// vector<int> b = {0,2};
// Number* A = new Number(a, 10, 1, 0);
// Number* B = new Number(b, 10, 1, 1);
// Number *ans = Sub(A, B);
// cout << ans->digits.size() << " " << ans->digits[0] << endl;
// vector<int> thresh_dig(1, 5);
// Number* Thresh = new Number(thresh_dig, 10, -10);
// Thresh->printNumber();
// Thresh->removeZeroes(true);
// cout << Number::compare(ans, Thresh) << endl;
// // ans->exponent = exp;
// // padding(&A,&B);
// ans->printNumber();
// cout << endl;
// }
// Rough : -
// 123 B 3 3-i-1 = 2 1
// 093 A 2 2-i-1 = 1 0
// 0
// 1 carry = 1
// 2
#endif