-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharbnum.cpp
More file actions
1402 lines (1168 loc) · 30.1 KB
/
arbnum.cpp
File metadata and controls
1402 lines (1168 loc) · 30.1 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
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// A simple arbitrary precision library and interactive text program
// Copyright © 2020, Dave McKellar
// Mozilla Public Licensed
#ifdef _MSC_VER
#include "stdafx.h"
#endif
#include <limits.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "arbnum.h"
//------------------------------------------------------------------------------
// Unsigned
static Unsigned gUnsignedZero(0);
static Unsigned gUnsignedOne(1);
static Unsigned gUnsignedTwo(2);
static const int UNASSIGNED = -1;
void Unsigned::pad(const size_t len) {
while (mDigits.size() < len) {
prepend(0);
}
}
void Unsigned::appendRight(const int digit, const size_t numberOfDigits) {
for (size_t i = 0; i < numberOfDigits; i++) {
append(digit);
}
}
void Unsigned::padShorterNumber(Unsigned &a, Unsigned &b) {
if (a.length() < b.length()) {
a.pad(b.length());
}
else {
b.pad(a.length());
}
}
void Unsigned::padShorterNumber(const Unsigned *&pA, const Unsigned *&pB, Unsigned &padded) {
if (pA->length() < pB->length()) {
padded = *pA;
padded.pad(pB->length());
pA = &padded;
}
else {
padded = *pB;
padded.pad(pA->length());
pB = &padded;
}
}
void Unsigned::zero() {
#if __cplusplus >= 201103L // Check if C++11 or later
for (auto &digit : mDigits) {
digit = 0;
}
#else
for (digits_t::iterator it = mDigits.begin(); it != mDigits.end(); it++) {
*it = 0;
}
#endif
}
bool Unsigned::isZero() const {
if (length() == 0) return true;
for (digits_t::const_iterator it = mDigits.begin(); it != mDigits.end(); it++) {
if (*it != 0) return false;
}
return true;
}
bool Unsigned::isOne() const {
if (length() != 1) return false;
return mDigits[0] == 1;
}
bool Unsigned::isTwo() const {
if (length() != 1) return false;
return mDigits[0] == 2;
}
inline bool isOdd(const int n) { return n % 2 != 0; }
inline bool isEven(const int n) { return ! isOdd(n); }
bool Unsigned::isOdd() const {
if (length() == 0) return false;
const int lastDigit = mDigits[length() - 1];
return ::isOdd(lastDigit);
}
bool Unsigned::isEven() const {
if (length() == 0) return true;
const int lastDigit = mDigits[length() - 1];
return ::isEven(lastDigit);
}
void Unsigned::trim() {
digits_t::iterator lastZero;
bool hits = false;
for (digits_t::iterator it = mDigits.begin(); it != mDigits.end(); it++) {
if (*it != 0) break;
lastZero = it;
hits = true;
}
if (!hits) return;
if (lastZero != mDigits.end()) {
lastZero++; // Because erase() doesn't include the last index
}
if (lastZero == mDigits.end()) {
lastZero--; // Its all zeros, keep one
}
mDigits.erase(mDigits.begin(), lastZero);
}
int Unsigned::charToInt(const char c) {
return c - '0';
}
char Unsigned::intToChar(const int n) {
if (n < 0) return '^';
return (char)(n + '0');
}
void Unsigned::clear() {
mDigits.clear();
}
void Unsigned::mkError() {
clear(); // Doesn't really set an error. But will case unit tests to fail which should raise a flag.
}
void Unsigned::saveNumber(const char *s) {
for (const char *p = s; *p; p++) {
if (*p == '.') {
fprintf(stderr, "Decimals are not supported -- only integers: %s\n", s);
mkError();
return;
}
if (!isdigit(*p)) {
fprintf(stderr, "Invalid number: %s\n", s);
mkError();
return;
}
append(charToInt(*p));
}
trim();
}
std::string Unsigned::toString() const {
std::string out = "";
for (digits_t::const_iterator it = mDigits.begin(); it != mDigits.end(); it++) {
out += intToChar(*it);
}
return out;
}
int Unsigned::toInt() const {
return atoi(toString().c_str());
}
long Unsigned::toLong() const {
return atol(toString().c_str());
}
long long Unsigned::toLongLong() const {
#if defined(_MSC_VER) && _MSC_VER <= 1400
#pragma message("Sorry " __FUNCTION__ " isn't supported on this compiler")
return atol(toString().c_str());
#else
return atoll(toString().c_str());
#endif
}
void Unsigned::set(const Unsigned &in) {
mDigits = in.mDigits;
}
Unsigned::Unsigned(const Unsigned &in) {
set(in);
}
Unsigned::Unsigned(const char *in) {
saveNumber(in);
}
Unsigned::Unsigned(const int n) {
char buf[100];
#ifdef __BORLANDC__
sprintf(buf, "%d", n);
#else
snprintf(buf, sizeof(buf), "%d", n);
#endif
saveNumber(buf);
}
Unsigned::Unsigned(const long n) {
char buf[100];
#ifdef __BORLANDC__
sprintf(buf, "%ld", n);
#else
snprintf(buf, sizeof(buf), "%ld", n);
#endif
saveNumber(buf);
}
Unsigned::Unsigned(const long long n) {
char buf[100];
#ifdef __BORLANDC__
sprintf(buf, "%lld", n);
#else
snprintf(buf, sizeof(buf), "%lld", n);
#endif
saveNumber(buf);
}
Unsigned::Unsigned(const bool b) {
set((int)b);
}
// a += b
// Both a and b will be modified so if you don't want that send in a copy
inline void Unsigned::addMutable(Unsigned &workingA, Unsigned &workingB) {
padShorterNumber(workingA, workingB);
int carry = 0;
for (int i = (int)workingA.length() - 1; i >= 0; i--) {
int digit = workingA[i] + workingB[i] + carry;
if (digit > 9) {
carry = 1;
digit -= 10;
}
else {
carry = 0;
}
workingA[i] = digit;
}
if (carry > 0) {
workingA.prepend(carry);
}
workingA.trim();
}
// result = a + b
Unsigned Unsigned::add(const Unsigned &a, const Unsigned &b) {
Unsigned workingA(a);
Unsigned workingB(b);
addMutable(workingA, workingB);
return workingA;
}
// a -= b
// Both a and b will be modified so if you don't want that send in a copy
void Unsigned::subtractMutable(Unsigned &workingA, Unsigned &workingB) {
padShorterNumber(workingA, workingB);
int borrow = 0;
for (int i = (int)workingA.length() - 1; i >= 0; i--) {
workingA[i] = workingA[i] - borrow;
if (workingB[i] > workingA[i]) {
workingA[i] = workingA[i] + 10;
borrow = 1;
}
else {
borrow = 0;
}
const int digit = workingA[i] - workingB[i];
workingA[i] = digit;
}
if (borrow > 0) {
fprintf(stderr, "Unsigned::subtract: Should not have a borrow\n");
workingA.mkError();
}
workingA.trim();
}
Unsigned Unsigned::subtract(const Unsigned &a, const Unsigned &b) {
Unsigned workingA(a);
Unsigned workingB(b);
subtractMutable(workingA, workingB);
return workingA;
}
Unsigned Unsigned::multiply(const Unsigned &a, const Unsigned &b) {
Unsigned sum(0);
Unsigned partProduct;
partProduct.pad(a.length() + b.length());
for (int i = 0; i < (int)b.length(); i++) {
const int bIndex = (int)b.length() - 1 - i;
const int bDigit = b.mDigits[bIndex];
int carry = 0;
partProduct.zero();
int j = 0;
for (; j < (int)a.length(); j++) {
const int aIndex = (int)a.length() -1 - j;
const int aDigit = a.mDigits[aIndex];
const int digit = bDigit * aDigit + carry;
const int ppIndex = (int)partProduct.length() -1 - j - i;
partProduct.mDigits[ppIndex] = digit % 10;
carry = digit / 10;
}
for(; carry > 0; j++) {
const int ppIndex = (int)partProduct.length() -1 - j - i;
partProduct.mDigits[ppIndex] = carry % 10;
carry /= 10;
}
sum.add(partProduct);
}
sum.trim();
return sum;
}
UnsignedDivide Unsigned::divideByOneWithRem(const Unsigned ÷nd) {
UnsignedDivide result(dividend, 0);
return result;
}
// https://en.wikipedia.org/wiki/Division_by_two
UnsignedDivide Unsigned::divideByTwoWithRem(const Unsigned ÷nd) {
Unsigned working(dividend);
UnsignedDivide result;
working.prepend(0);
const int len1 = (int)working.length() - 1;
int first, second;
for (int i = 0; i < len1; i++) {
first = working.mDigits[i];
second = working.mDigits[i + 1];
int save;
if (::isEven(first)) {
switch(second) {
case 0:
case 1:
save = 0;
break;
case 2:
case 3:
save = 1;
break;
case 4:
case 5:
save = 2;
break;
case 6:
case 7:
save = 3;
break;
case 8:
case 9:
save = 4;
break;
}
}
else {
switch(second) {
case 0:
case 1:
save = 5;
break;
case 2:
case 3:
save = 6;
break;
case 4:
case 5:
save = 7;
break;
case 6:
case 7:
save = 8;
break;
case 8:
case 9:
save = 9;
break;
}
}
result.quotient.append(save);
}
if (::isOdd(second)) {
result.remainder = 1;
}
result.trim();
return result;
}
// Division by repeated subtraction
UnsignedDivide Unsigned::divideWithRemSlow(const Unsigned ÷nd, const Unsigned &divisor) {
UnsignedDivide result(0, dividend);
if (divisor <= gUnsignedTwo) {
switch(divisor.toInt()) {
case 0:
fprintf(stderr, "Division by zero\n");
result.quotient.mkError();
return result;
case 1:
return divideByOneWithRem(dividend);
case 2:
return divideByTwoWithRem(dividend);
}
}
while (result.remainder >= divisor) {
result.quotient++;
result.remainder.subtract(divisor);
}
result.trim();
return result;
}
// Helper for divideWithRemFast()
Unsigned Unsigned::findDivisibleSizedChunk(const Unsigned &runningDividend, const Unsigned ÷nd, const Unsigned &divisor, int &iDividendPos, bool &fits) {
Unsigned chunk;
iDividendPos = 0;
for (; iDividendPos < (int)dividend.length(); iDividendPos++) {
int digit;
if (runningDividend.mDigits[iDividendPos] >= 0) {
digit = runningDividend.mDigits[iDividendPos];
}
else {
digit = dividend.mDigits[iDividendPos];
}
chunk.append(digit);
if (chunk >= divisor) {
fits = true;
return chunk;
}
}
fits = false;
return chunk;
}
// https://en.wikipedia.org/wiki/Long_division#Example_with_multi-digit_divisor
UnsignedDivide Unsigned::divideWithRemFast(const Unsigned ÷nd, const Unsigned &divisor) {
Unsigned runningDividend;
UnsignedDivide result;
result.quotient.pad(dividend.length());
runningDividend.appendRight(UNASSIGNED, dividend.length());
if (divisor <= gUnsignedTwo) {
switch(divisor.toInt()) {
case 0:
fprintf(stderr, "Division by zero\n");
result.quotient.mkError();
return result;
case 1:
return divideByOneWithRem(dividend);
case 2:
return divideByTwoWithRem(dividend);
}
}
int iDividendPos = 0;
bool fits;
for (;;) {
const Unsigned chunk = findDivisibleSizedChunk(runningDividend, dividend, divisor, iDividendPos, fits);
if (!fits) {
result.remainder = chunk;
break;
}
const UnsignedDivide partDivide = divideWithRemSlow(chunk, divisor);
const Unsigned partProd = subtract(chunk, partDivide.remainder);
result.quotient[iDividendPos] = partDivide.quotient.mDigits[0];
runningDividend = subtract(chunk, partProd);
runningDividend.appendRight(UNASSIGNED, dividend.length() - iDividendPos - 1);
runningDividend.pad(dividend.length());
}
result.trim();
return result;
}
Unsigned Unsigned::divide(const Unsigned &a, const Unsigned &b) {
return divideWithRemFast(a, b).quotient;
}
Unsigned Unsigned::half(const Unsigned &a) {
return divideByTwoWithRem(a).quotient;
}
Unsigned Unsigned::mod(const Unsigned &a, const Unsigned &b) {
return divideWithRemFast(a, b).remainder;
}
Unsigned Unsigned::pow(const Unsigned &a, const Unsigned &n) {
if (n.isZero()) return gUnsignedOne;
const Unsigned x = pow(a, half(n));
if (n.isEven()) {
return x * x;
}
else {
return a * x * x;
}
}
// Euler's method
Unsigned Unsigned::gcd(const Unsigned &a, const Unsigned &b) {
if (a.isZero()) return b;
return gcd(b % a, a);
}
// Newton's method
Unsigned Unsigned::sqrt(const Unsigned &s) {
Unsigned x0 = half(s);
if (x0.isZero()) return s;
Unsigned x1 = half(x0 + s / x0);
while(x1 < x0) {
x0 = x1;
x1 = half(x0 + s / x0);
}
return x0;
}
// Call rand() wantedDigits times and use the least significant digit each time
Unsigned Unsigned::random(const Unsigned &wantedDigits) {
static bool bRandInitialized = false;
if (!bRandInitialized) {
bRandInitialized = true;
srand((unsigned int)time(NULL));
}
Unsigned result;
const long n = wantedDigits.toLong();
if (n <= 0) return 0;
for (long i = 0; i < n; i++) {
const int r = rand();
const int digit = r % 10;
result.append(digit);
}
return result;
}
// By Soma Mbadiwe on https://stackoverflow.com/questions/15743192/check-if-number-is-prime-number
Unsigned Unsigned::isPrime(const Unsigned &a) {
if (a <= 1) return false;
if (a == 2 || a == 3 || a == 5) return true;
if (a.isEven() || a % 3 == 0 || a % 5 == 0) return false;
const Unsigned boundary = sqrt(a);
for (Unsigned i = 6; i <= boundary; i += 6) {
if (a % (i + 1) == 0 || a % (i + 5) == 0) {
return false;
}
}
return true;
}
void Unsigned::add(const Unsigned &other) {
Unsigned workingB(other);
addMutable(*this, workingB);
}
void Unsigned::subtract(const Unsigned &other) {
Unsigned workingB(other);
subtractMutable(*this, workingB);
}
void Unsigned::multiply(const Unsigned &other) {
set(multiply(*this, other));
}
void Unsigned::divide(const Unsigned &other) {
set(divide(*this, other));
}
void Unsigned::mod(const Unsigned &other) {
set(mod(*this, other));
}
void Unsigned::pow(const Unsigned &other) {
set(pow(*this, other));
}
int Unsigned::compare(const Unsigned &aIn, const Unsigned &bIn) {
const Unsigned *pA = &aIn;
const Unsigned *pB = &bIn;
Unsigned padded;
padShorterNumber(pA, pB, padded);
for (size_t i = 0; i < pA->length(); i++) {
if (pA->mDigits[i] < pB->mDigits[i]) return -1;
if (pA->mDigits[i] > pB->mDigits[i]) return 1;
}
return 0;
}
Unsigned Unsigned::operator++(int) {
add(gUnsignedOne);
return *this;
}
Unsigned Unsigned::operator--(int) {
subtract(gUnsignedOne);
return *this;
}
//------------------------------------------------------------------------------
// ArbNum
static ArbNum gArbNumZero(0);
static ArbNum gArbNumOne(1);
static ArbNum gArbNumIntMin(INT_MIN);
static ArbNum gArbNumIntMax(INT_MAX);
static ArbNum gArbNumLongMin(LONG_MIN);
static ArbNum gArbNumLongMax(LONG_MAX);
void ArbNum::set(const ArbNum &in) {
mSpecial = in.mSpecial;
mSign = in.mSign;
mUnsigned = in.mUnsigned;
}
ArbNum::ArbNum(const Unsigned &in) {
clear();
mUnsigned = in;
}
ArbNum::ArbNum(const ArbNum &in) {
set(in);
}
ArbNum::ArbNum(const char *s) {
saveNumber(s);
}
ArbNum::ArbNum(const int n) {
char buf[100];
#ifdef __BORLANDC__
sprintf(buf, "%d", n);
#else
snprintf(buf, sizeof(buf), "%d", n);
#endif
saveNumber(buf);
}
ArbNum::ArbNum(const long n) {
char buf[100];
#ifdef __BORLANDC__
sprintf(buf, "%ld", n);
#else
snprintf(buf, sizeof(buf), "%ld", n);
#endif
saveNumber(buf);
}
ArbNum::ArbNum(const long long n) {
char buf[100];
#ifdef __BORLANDC__
sprintf(buf, "%lld", n);
#else
snprintf(buf, sizeof(buf), "%lld", n);
#endif
saveNumber(buf);
}
ArbNum::ArbNum(const bool b) {
set((int) b);
}
void ArbNum::clear() {
mSpecial = SPEC_NORMAL;
mkPositive();
mUnsigned.clear();
}
void ArbNum::saveNumber(const char *s) {
clear();
if (*s == '-') {
mkNegative();
s++;
}
mUnsigned.saveNumber(s);
}
ArbNum ArbNum::abs(const ArbNum &a) {
return a.mUnsigned;
}
ArbNum ArbNum::sign(const ArbNum &a) {
return a.mSign;
}
ArbNum ArbNum::add(const ArbNum &a, const ArbNum &b) {
ArbNum result;
if (a.isPositiveOrZero() && b.isPositiveOrZero()) {
// Both positive => will stay positive
result.mUnsigned = Unsigned::add(a.mUnsigned, b.mUnsigned);
}
else if (a.isPositiveOrZero() && b.isNegativeOrZero()) {
// Remove sign from other, subtract other from this
ArbNum workingB(b);
workingB.mkPositive();
result = ArbNum::subtract(a, workingB); // Need to use ArbNum::subtract() because it checks to see which larger
}
else if (a.isNegativeOrZero() && b.isPositiveOrZero()) {
// -a + b = b - a
ArbNum workingA(a);
workingA.mkPositive();
result = ArbNum::subtract(b, workingA); // Need to use ArbNum::subtract() because it checks to see which larger
}
else if (a.isNegativeOrZero() && b.isNegativeOrZero()) {
// Both negative => will stay negative
result.mkNegative();
result.mUnsigned = Unsigned::add(a.mUnsigned, b.mUnsigned);
}
else {
fprintf(stderr, "add: unknown case\n");
result.mkError();
}
return result;
}
ArbNum ArbNum::subtract(const ArbNum &a, const ArbNum &b) {
ArbNum result;
if (a.isPositiveOrZero() && b.isPositiveOrZero()) {
if (a.mUnsigned < b.mUnsigned) {
// a - b = - (b - a)
result.mkNegative();
result.mUnsigned = Unsigned::subtract(b.mUnsigned, a.mUnsigned);
}
else {
// Easy a - b
result.mUnsigned = Unsigned::subtract(a.mUnsigned, b.mUnsigned);
}
}
else if (a.isPositiveOrZero() && b.isNegativeOrZero()) {
// a - (-b) = a + b
// Sign is already positive
result.mUnsigned = Unsigned::add(a.mUnsigned, b.mUnsigned);
}
else if (a.isNegativeOrZero() && b.isPositiveOrZero()) {
// (-a) - b = - (a + b)
result.mkNegative();
result.mUnsigned = Unsigned::add(a.mUnsigned, b.mUnsigned);
}
else if (a.isNegativeOrZero() && b.isNegativeOrZero()) {
// (-a) - (-b) = b - a
ArbNum workingA(a);
ArbNum workingB(b);
workingA.mkPositive();
workingB.mkPositive();
result = ArbNum::subtract(workingB, workingA); // Recursive
}
else{
fprintf(stderr, "subtract: unknown case\n");
result.mkError();
}
return result;
}
ArbNum ArbNum::multiply(const ArbNum &a, const ArbNum &b) {
ArbNum result;
result.mUnsigned = Unsigned::multiply(a.mUnsigned, b.mUnsigned);
result.mSign = a.mSign * b.mSign;
return result;
}
// https://en.wikipedia.org/wiki/Division_algorithm
ArbNumDivide ArbNum::divideWithRem(const ArbNum ÷nd, const ArbNum &divisor) {
ArbNumDivide result;
if (divisor.isZero()) {
fprintf(stderr, "Division by zero\n");
result.quotient.mkError();
return result;
}
if (divisor.isNegative()) {
ArbNum workingDivisor(divisor);
workingDivisor.mkPositive();
result = divideWithRem(dividend, workingDivisor); // Recursive
result.quotient.flipSign();
return result;
}
if (dividend.isNegative()) {
ArbNum workingDividend(dividend);
workingDividend.mkPositive();
result = divideWithRem(workingDividend, divisor); // Recursive
if (result.remainder.isZero()) {
result.quotient.flipSign();
return result;
}
else {
result.quotient.flipSign();
// We differ from the page Wikipedia page here
result.remainder.flipSign();
return result;
}
}
// Both are positive
const UnsignedDivide udivide = Unsigned::divideWithRemFast(dividend.mUnsigned, divisor.mUnsigned);
result.quotient.mUnsigned = udivide.quotient;
result.remainder.mUnsigned = udivide.remainder;
return result;
}
ArbNum ArbNum::divide(const ArbNum ÷nd, const ArbNum &divisor) {
return divideWithRem(dividend, divisor).quotient;
}
ArbNum ArbNum::mod(const ArbNum ÷nd, const ArbNum &divisor) {
return divideWithRem(dividend, divisor).remainder;
}
ArbNum ArbNum::min(const ArbNum &a, const ArbNum &b) {
return a < b ? a : b;
}
ArbNum ArbNum::max(const ArbNum &a, const ArbNum &b) {
return a > b ? a : b;
}
ArbNum ArbNum::doNot(const ArbNum &a) {
return a.isZero() ? gArbNumOne : gArbNumZero;
}
ArbNum ArbNum::pow(const ArbNum &a, const ArbNum &n) {
ArbNum result = Unsigned::pow(a.mUnsigned, n.mUnsigned);
if (a.isNegative()) {
result.mSign = n.mUnsigned.isEven() ? 1 : -1;
}
return result;
}
ArbNum ArbNum::gcd(const ArbNum &a, const ArbNum &b) {
return Unsigned::gcd(a.mUnsigned, b.mUnsigned);
}
ArbNum ArbNum::sqrt(const ArbNum &a) {
if (a.isNegative()) {
ArbNum result;
result.mkError();
return result;
}
return Unsigned::sqrt(a.mUnsigned);
}
ArbNum ArbNum::random(const ArbNum &n) {
return Unsigned::random(n.mUnsigned);
}
ArbNum ArbNum::isPrime(const ArbNum &a) {
if (a.isNegative()) return false;
return Unsigned::isPrime(a.mUnsigned);
}
ArbNum ArbNum::factorial(const ArbNum &count) {
if (count <= gArbNumOne) return gArbNumOne;
return factorial(count - gArbNumOne) * count;
}
void ArbNum::add(const ArbNum &other) {
set(add(*this, other));
}
void ArbNum::subtract(const ArbNum &other) {
set(subtract(*this, other));
}
void ArbNum::multiply(const ArbNum &other) {
set(multiply(*this, other));
}
void ArbNum::divide(const ArbNum &other) {
set(divide(*this, other));
}
void ArbNum::mod(const ArbNum &other) {
set(mod(*this, other));
}
void ArbNum::pow(const ArbNum &other) {
set(pow(*this, other));
}
std::string ArbNum::toString() const {
std::string out = "";
if (isIgnore()) {
return "ignore";
}
else if (isError()) {
return "error";
}
if (mSign < 0) {
out += "-";
}
out += mUnsigned.toString();
return out;
}
int ArbNum::toInt() const {
if (isZero()) return 0;
if (*this < gArbNumIntMin) {
fprintf(stderr, "Too small for an int: %s\n", toString().c_str());
return -1;
}
if (*this > gArbNumIntMax) {
fprintf(stderr, "Too large for an int: %s\n", toString().c_str());
return -1;
}
return atoi(toString().c_str());
}
long ArbNum::toLong() const {
if (isZero()) return 0;
if (*this < gArbNumLongMin) {
fprintf(stderr, "Too small for a long: %s\n", toString().c_str());
return -1;
}
if (*this > gArbNumLongMax) {
fprintf(stderr, "Too large for a long: %s\n", toString().c_str());
return -1;
}
return atol(toString().c_str());
}