-
Notifications
You must be signed in to change notification settings - Fork 0
/
BigInt.cpp
453 lines (394 loc) · 12.1 KB
/
BigInt.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
#include <cassert>
#include <cmath> // std::floor
#include <exception> // std::invalid_argument
#include "BigInt.h"
// vvvvvvvvvv HELPER FUNCTIONS vvvvvvvvvv
// remove leading zeros
static void rem_lzeros(std::vector<int>& a) {
while (a.size() > 1 && a.back() == 0) {
a.pop_back();
}
}
// compute a mod b
static int mod(const int a, const int b) {
return a - b * int(std::floor(float(a) / b));
}
// base routine for adding two nonnegative integers
// REQUIRES: This method assumes that result is an empty vector to which digits
// from the result will be appended as they are computed.
static void add(const std::vector<int>& lhs,
const std::vector<int>& rhs,
std::vector<int>& result, const int base) {
assert(result.size() == 0);
size_t i = 0;
size_t j = 0;
int carry = 0;
while (i < lhs.size() || j < rhs.size()) {
int partial_sum = carry;
if (i < lhs.size()) {
partial_sum += lhs[i];
++i;
}
if (j < rhs.size()) {
partial_sum += rhs[j];
++j;
}
result.push_back(partial_sum % base);
carry = int(partial_sum / base);
}
if (carry) {
result.push_back(carry);
}
}
// base routine for subtracting two nonnegative integers
// REQUIRES: This method assumes that result is an empty vector to which digits
// from the result will be appended as they are computed.
static void subtract(const std::vector<int>& lhs,
const std::vector<int>& rhs,
std::vector<int>& result, const int base) {
assert(result.size() == 0);
size_t i = 0;
size_t j = 0;
int borrow = 0;
while (i < lhs.size() || j < rhs.size()) {
int partial_sub = borrow;
if (i < lhs.size()) {
partial_sub += lhs[i];
++i;
}
if (j < rhs.size()) {
partial_sub -= rhs[j];
++j;
}
result.push_back(mod(partial_sub, base));
borrow = int(std::floor(float(partial_sub) / base));
}
assert(borrow == 0);
rem_lzeros(result);
}
// base routine for mutliplying two nonnegative integers
// REQUIRES: This method assumes that result is an empty vector to which digits
// from the result will be appended as they are computed.
static void multiply(const std::vector<int>& lhs,
const std::vector<int>& rhs,
std::vector<int>& result, const int base) {
assert(result.size() == 0);
int k;
for (size_t i = 0; i < lhs.size() + rhs.size(); ++i) {
result.push_back(0);
}
for (size_t j = 0; j < rhs.size(); ++j) {
k = 0;
for (size_t i = 0; i < lhs.size(); ++i) {
int t = lhs[i] * rhs[j] + result[i + j] + k;
result[i + j] = mod(t, base);
k = int(t / base);
}
result[lhs.size() + j] = k;
}
rem_lzeros(result);
}
// a simpler division algorithm for the case when the divisor is
// of single precision (i.e. 1 < divisor < base)
static void divide_single_precision(const std::vector<int>& lhs,
const std::vector<int>& rhs,
std::vector<int>& result,
const int base) {
assert(rhs.size() == 1 && rhs[0] != 0);
// there must be a better way to implement this algorithm that doesn't
// require resizing the result vector before calculating (O(n)) and then
// iterating through it to compute and insert digits (O(n))
result.resize(lhs.size());
assert(result.size() == lhs.size());
int v = rhs[0];
int d_partial = 0;
for (size_t i = lhs.size(); i-- > 0; ) {
d_partial = d_partial * base + lhs[i];
int digit = d_partial / v;
result[i] = digit;
d_partial -= digit * v;
}
rem_lzeros(result);
// should this function return the remainder somehow??
}
// base routine for dividing two nonnegative integers
// from Knuth, The Art of Computer Programming (Seminumerical Algorithms):
//
// given nonnegative integers
// u = (u_{m+n-1}...u_{0})_{b}
// and
// v = (v{n-1}...v_{0})_{b},
// where the leading digit of v n.e. 0 and n > 1,
// this recipe forms the radix-b quotient
// floor(u / v) = (q_{m}...q_{0})_{b}
// and the remainder
// u mod v = (r_{n-1}...r_{0})_{b}.
//
static void divide(const std::vector<int>& lhs,
const std::vector<int>& rhs,
std::vector<int>& result, const int base) {
if (rhs.size() == 1) {
divide_single_precision(lhs, rhs, result, base);
return;
}
else {
assert(false);
}
}
// ^^^^^^^^^^ HELPER FUNCTIONS ^^^^^^^^^^
//
// vvvvvvvvvv CONSTRUCTORS vvvvvvvvvv
BigInt::BigInt()
: digits({0}), negative(false) { }
BigInt::BigInt(const std::string& val) {
if (val.empty()) {
throw std::invalid_argument(
"BigInt cannot be initialized from an empty string."
);
}
if (val.front() == '-') {
if (val.size() == 1) {
throw std::invalid_argument(
"Initializer string must contain a decimal value."
);
}
negative = true;
}
else {
negative = false;
}
for (auto it = val.rbegin(); it != val.rend(); ++it) {
if (*it == '-' && next(it) == val.rend()) {
continue;
}
if (*it < '0' || *it - '0' >= BASE) {
throw std::invalid_argument("Bad initializer digit.");
}
digits.push_back(*it - '0');
}
}
BigInt::BigInt(const char* val)
: BigInt(std::string(val)) { }
BigInt::BigInt(const std::vector<int>& digits_in, const bool negative_in)
: digits(digits_in), negative(negative_in) { }
// assign to a BigInt from a string representation of an integer
//
// * is this a good idea? I am implementing this with convenience
// in mind, for example, to reassign to a previously-created BigInt a:
// a = "12345"; (instead of/in addition to)
// a = BigInt("12345");
//
// Is this confusing more than it is helpful?
BigInt& BigInt::operator=(const std::string& val) {
return *this = BigInt(val);
}
BigInt::BigInt(const int val) {
int n = val >= 0 ? val : -val;
while (n > 0) {
int dig = n % 10;
n = (n - dig) / 10;
digits.push_back(dig);
}
negative = val < 0;
}
BigInt& BigInt::operator=(const char* val) {
return *this = BigInt(std::string(val));
}
// ^^^^^^^^^^ CONSTRUCTORS ^^^^^^^^^^
bool BigInt::is_negative() const {
return negative;
}
// design question: how long should an unitilialized BigInt be? Should
// a BigInt even have a length attribute at all?
int BigInt::length() const {
return int(digits.size());
}
// vvvvvvvvvv ARITHMETIC-ASSIGNMENT OPERATORS vvvvvvvvvv
BigInt& BigInt::operator+=(const BigInt& rhs) {
// define in terms of the overloaded addition operator
return *this = *this + rhs;
}
BigInt& BigInt::operator-=(const BigInt& rhs) {
// define in terms of the overloaded subtraction operator
return *this = *this - rhs;
}
BigInt& BigInt::operator*=(const BigInt& rhs) {
// define in terms of the overloaded subtraction operator
return *this = *this * rhs;
}
BigInt& BigInt::operator/=(const BigInt& rhs) {
assert(false);
}
// ^^^^^^^^^^ ARITHMETIC-ASSIGNMENT OPERATORS ^^^^^^^^^^
//
// vvvvvvvvvv ARITHMETIC OPERAORS vvvvvvvvvv
BigInt BigInt::operator+(const BigInt &rhs) const {
BigInt result;
std::vector<int> result_digs;
if (!(this->is_negative() || rhs.is_negative())) {
add(this->digits, rhs.digits, result_digs, BASE);
result = {result_digs, false};
}
else if (this->is_negative() && rhs.is_negative()) {
add(this->digits, rhs.digits, result_digs, BASE);
result = {result_digs, true};
}
else {
if (this->is_negative()) {
result = rhs - (-(*this));
}
else {
result = *this - (-(rhs));
}
}
return result;
}
BigInt BigInt::operator-(const BigInt &rhs) const {
BigInt result;
std::vector<int> result_digs;
if(!(this->is_negative() || rhs.is_negative())) {
if (*this >= rhs) {
subtract(this->digits, rhs.digits, result_digs, BASE);
result = {result_digs, false};
}
else {
subtract(rhs.digits, this->digits, result_digs, BASE);
result = {result_digs, true};
}
}
else if (this->is_negative() && rhs.is_negative()) {
result = -rhs - -(*this);
}
else {
if (this->is_negative()) {
add(this->digits, rhs.digits, result_digs, BASE);
result = {result_digs, true};
}
else {
add(this->digits, rhs.digits, result_digs, BASE);
result = {result_digs, false};
}
}
return result;
}
BigInt BigInt::operator*(const BigInt &rhs) const {
BigInt result;
std::vector<int> result_digs;
multiply(this->digits, rhs.digits, result_digs, BASE);
bool neg = this->is_negative() == rhs.is_negative() ? false : true;
result = {result_digs, neg};
return result;
}
BigInt BigInt::operator/(const BigInt &rhs) const {
BigInt result;
std::vector<int> result_digs;
divide(this->digits, rhs.digits, result_digs, BASE);
bool neg = this->is_negative() == rhs.is_negative() ? false : true;
result = {result_digs, neg};
return result;
}
// ^^^^^^^^^^ ARITHMETIC OPERATORS ^^^^^^^^^^
//
// vvvvvvvvvv UNARY OPERATORS vvvvvvvvvv
BigInt BigInt::operator+() const {
return BigInt(this->digits, this->negative);
}
BigInt BigInt::operator-() const {
bool negative_in = negative ? false : true;
return BigInt(this->digits, negative_in);
}
BigInt& BigInt::operator++() {
return *this += BigInt("1");
}
BigInt& BigInt::operator--() {
return *this -= BigInt("1");
}
BigInt BigInt::operator++(int) {
BigInt copy = *this;
*this += BigInt("1");
return copy;
}
BigInt BigInt::operator--(int) {
BigInt copy = *this;
*this -= BigInt("1");
return copy;
}
// ^^^^^^^^^^ UNARY OPERATORS ^^^^^^^^^^
//
// vvvvvvvvv COMPARISON OPERATORS vvvvvvvvv
bool BigInt::operator==(const BigInt &rhs) const {
if (this->digits.size() != rhs.digits.size() ||
this->is_negative() != rhs.is_negative()) {
return false;
}
else {
size_t i = 0;
while (i < this->digits.size() && i < rhs.digits.size()) {
if (this->digits[i] != rhs.digits[i]) {
return false;
}
++i;
}
return true;
}
}
bool BigInt::operator!=(const BigInt &rhs) const {
return !(*this == rhs);
}
bool BigInt::operator<(const BigInt &rhs) const {
if (this->is_negative() && !rhs.is_negative()) {
return true;
}
else if (!this->is_negative() && rhs.is_negative()) {
return false;
}
else { // *this and rhs have the same sign
if (this->digits.size() < rhs.digits.size()) {
return true;
}
else if (this->digits.size() > rhs.digits.size()) {
return false;
}
else {
size_t i = 0;
while (i < this->digits.size() && i < rhs.digits.size()) {
if (this->digits[i] < rhs.digits[i]) {
return true;
}
++i;
}
return false;
}
}
}
bool BigInt::operator>(const BigInt &rhs) const {
return !(*this == rhs || *this < rhs);
}
bool BigInt::operator<=(const BigInt &rhs) const {
return (*this == rhs || *this < rhs);
}
bool BigInt::operator>=(const BigInt &rhs) const {
return !(*this < rhs);
}
// ^^^^^^^^^^ COMPARISON OPERATORS ^^^^^^^^^^
std::string BigInt::to_string() const {
std::string s_out;
if (is_negative()) {
s_out.push_back('-');
}
for (auto it = digits.rbegin(); it != digits.rend(); ++it) {
s_out.push_back(*it + '0');
}
return s_out;
}
std::ostream& operator<<(std::ostream &os, const BigInt &val)
{
if (val.is_negative()) {
os << '-';
}
for (auto it = val.digits.rbegin(); it != val.digits.rend(); ++it)
{
os << *it;
}
return os;
}