-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNum.java
1361 lines (1134 loc) · 145 KB
/
Num.java
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
package rsn170330.lp1;
/**
* CS 5V81.001. Implementation of data structures and algorithms
* Long Project LP1: Integer arithmetic with arbitrarily large numbers
* @author Rahul Nalawade (rsn170330)
* @author Dhwani Raval (dsr170230)
* @author Varun Parashar (vxp171830)
* @author Arpita Agrawal (aua170030)
* @author Simran Rawlani (sxr174130)
* @author Yash Madane (yxm172130)
*
* Date: Sunday, September 23, 2018
*/
import java.util.HashSet;
import java.util.Stack;
import java.util.HashMap;
import java.util.Set;
import java.util.Map;
public class Num implements Comparable<Num> {
// defaultBase: Base in which input and output numbers are evaluated
static long defaultBase = 10;
// base: Base responsible for fast calculations. Larger the base, faster the computations.
long base = 1000000000; //NOTE: Keep it in powers of 10 AND 10 <= base <= 10^9
int digits = (int) Math.log10(base()); // base = 10^digits
// Main attributes of a Num:
private long[] arr; // array to store arbitrarily large integers
// boolean flag to represent negative numbers
private boolean isNegative;
private int len; // actual number of elements of array that are used
/**
* Converts String s (a number) into Num. Initialize isNegative, arr, and len.
* @param s the input string
* @throws NumberFormatException
*/
public Num(String s) throws NumberFormatException {
isNegative = false;
/**
* oriStrLen: original string length of s
* trunStrLen: truncated string length after ignoring '-' sign and leading 0s
* non0: index keeping track of first nonzero character
* count0: total leading 0s in a string
*/
int oriStrLen = s.length();
int trunStrLen = oriStrLen, non0 = 0, count0 = 0;
String validStr = "[-]([0-9]+)||([0-9]+)"; // RegEx for valid String
// When invalid string entered
if (oriStrLen == 0 || s.isEmpty() ||
(oriStrLen > 1 && !s.substring(0, 2).matches(validStr))) {
throw new NumberFormatException("Invalid String \n");
}
// Assigning proper Sign
this.isNegative = (s.charAt(0) == '-')? true : false;
// Truncating '- sign' character, if present
if (isNegative) {
trunStrLen = oriStrLen - 1;
non0 = 1;
}
char[] sChar = s.toCharArray();
// incrementing non0 to keep track of first nonZero element.
while (non0 < oriStrLen && sChar[non0] == '0') {
non0++;
count0++;
}
// For -000000000000 to be just 0
if (trunStrLen == count0)
isNegative = false;
// Removing leading zeros
if (count0 > 0)
trunStrLen = trunStrLen - count0;
// trunStrLen cannot be further truncated. So, assign a correct len
this.len = (int) Math.ceil((double) trunStrLen / digits);
// When s is "0"
if (len == 0) {
len = 1; // still a valid 'digit'
arr = new long[1];
arr[0] = Long.parseLong(s);
}
else {
arr = new long[len];
int i = 0, k = 0;
int index = oriStrLen - 1;
char[] charDigit = new char[digits];
String strDigit;
// Extracting the numbers out of String
while (non0 <= index && i < len) {
k = digits - 1;
// Copying chunk of characters of length 'digits' or less
while (-1 < k && non0 <= index) {
charDigit[k--] = sChar[index--];
}
// if less then remaining characters are padded with '0'
while (-1 < k) { charDigit[k--] = '0'; }
strDigit = new String(charDigit);
// a new digit is added as a long in arr
this.arr[i++] = Long.parseLong(strDigit);
}
}
}
/**
* Reads the number x (in defaultBase), to create Num in base = this.base
* storing all it's digits long[] arr with least significant at arr[0] and so on.
* @param x the number
*/
public Num(long x) {
isNegative = false;
// When x is Negative, making it positive with flag isNegative as true
if (x < 0) {
this.isNegative = true;
x = -1 * x;
}
double lengthArr = 0;
// When x = 0, lengthArr = -Infinity
if (x == 0) {
lengthArr = 1;
}
// No of digits in this.Num = log_base (x) + 1 = log(x)/log(base) + 1
else {
lengthArr = ((Math.log((double) x)) / (Math.log((double) base))) + 1;
}
this.len = (int) lengthArr; // Real to integer (floor function)
arr = new long[this.len];
long n = x;
// Iteratively pass appropriate digit to this.arr (array of long)
for (int i = 0; i < len; i++) {
arr[i] = n % base();
n /= base();
}
}
// Constructor that does nothing
private Num() {
}
/**
* Addition of two numbers Num a and Num b.
* Precondition: a and b must be in the same base.
* @param a the large number
* @param b the large number
* @return the large sum of a and b
*/
public static Num add(Num a, Num b) {
Num out = new Num();
// When (-) + (-)
if (a.isNegative && b.isNegative) {
out = out.unsignedAdd(a, b);
out.isNegative = true;
}
// When (+) + (+)
else if (!a.isNegative && !b.isNegative) {
out = out.unsignedAdd(a, b);
out.isNegative = false;
}
// When you need to find the difference
else {
// When |a| < |b|
if (a.compareTo(b) < 0) {
out = out.normalSubtract(b, a); // find the difference
out.isNegative = b.isNegative; // give bigger number sign
} else {
out = out.normalSubtract(a, b); // find the difference
out.isNegative = a.isNegative; // give bigger number sign
}
}
return out;
}
/**
* Unsigned addition of two numbers Num a and Num b.
* Precondition: a and b must be in the same base.
* @param a the large number
* @param b the large number
* @return the large sum of a and b
*/
private Num unsignedAdd(Num x, Num y) {
int pA = 0, pB = 0; // Pointers as indices of each Number array
long carry = 0;
long sum = 0;
// trimming unnecessary leading zeros, if any.
// Updating to appropriate a.len and b.len as well
Num a = trimZeros(x);
Num b = trimZeros(y);
Num out = new Num();
out.len = Math.max(a.len, b.len);
out.arr = new long[out.len + 1]; // NOTE: out.arr initialized to long[out.len + 1]*
int index = 0;
// While both arrays have corresponding element
while (pA < a.len && pB < b.len) {
// Elementary way of adding digit by digit
sum = a.arr[pA] + b.arr[pB] + carry;
out.arr[index] = (sum % base);
carry = (sum / base); // would be 1 or 0
// incrementing all 3 Indices
pA++; pB++; index++;
}
// Now, one of the number is exhausted
// When b is exhausted, while a still has element(s)
while (pA < a.len) {
// same as above
sum = a.arr[pA] + carry;
out.arr[index] = (sum % base);
carry = (sum / base);
pA++; index++;
}
// When a is exhausted, while b still has element(s)
while (pB < b.len) {
// same as above
sum = b.arr[pB] + carry;
out.arr[index] = (sum % base);
carry = (sum / base);
pB++; index++;
}
// If there's still a carry forwarded
if (carry > 0) {
out.arr[index] = carry;
out.len++;
}
// returning without any leading zeros
return trimZeros(out);
}
/**
* Trimming unnecessary leading zeros from x.
* Keeping sign intact, updates 'a.len' and 'a.arr' from x
* @param x the input number
* @return the trimmed number a
*/
private Num trimZeros(Num x) {
Num a = new Num();
a.isNegative = x.isNegative; // sign as it was
int aLen = x.len; // initialized
// reduce by 1 every-time you have a leading zero
while (x.arr[aLen - 1] == 0) {
aLen--;
// When all zeros, eventually ended up making aLen = 0
if (aLen == 0) {
aLen++;
break;
}
}
// Initialize and returning appropriately
a.arr = new long[aLen];
for (int i = 0; i < aLen; i++) {
a.arr[i] = x.arr[i];
}
a.len = aLen;
return a;
}
/**
* Subtraction of Num b from Num a.
* NOTE: Left associativity is maintained.
* @param a the input number
* @param b the input number
* @return the difference
*/
public static Num subtract(Num a, Num b) {
Num out = new Num();
// When a-b = (-) - (+)
if (a.isNegative && !b.isNegative) {
out = out.unsignedAdd(a, b);
out.isNegative = true;
}
// When a-b = (+) - (-)
else if (!a.isNegative && b.isNegative) {
out = out.unsignedAdd(a, b);
out.isNegative = false;
}
// When a-b needs to find the difference |a|-|b|
else {
// When |a| < |b|
if (a.compareTo(b) < 0) {
out = out.normalSubtract(b, a); // find the difference
out.isNegative = !b.isNegative; // give bigger number sign* -(-b) is +ve
} else {
out = out.normalSubtract(a, b); // find the difference
out.isNegative = a.isNegative; // give bigger number sign
}
}
return out;
}
/**
* Difference of two numbers ignoring the sign.
* Precondition: x >= y
* @param x the greater number
* @param y the smaller number
* @return the difference
*/
private Num normalSubtract(Num x, Num y) {
int pA = 0, pB = 0; // Pointers as indices of array of numbers
long borrow = 0;
long digitDiff = 0;
// Trimming unnecessary leading zeros, if any.
// Updating to appropriate a.len and b.len as well
Num a = trimZeros(x);
Num b = trimZeros(y);
Num out = new Num();
out.len = Math.max(a.len, b.len);
out.arr = new long[out.len]; // but out.arr initialized to long[out.len]* (not out.len + 1)
int index = 0;
// While both arrays have corresponding element
while (pA < a.len && pB < b.len) {
// Elementary way of subtracting digit by digit,
// WITH subtracting a BORROW taken earlier
digitDiff = a.arr[pA] - b.arr[pB] - borrow;
// When you don't need to take a borrow
if (digitDiff >= 0) {
out.arr[index] = digitDiff;
borrow = 0;
// Incrementing all the Indices
pA++; pB++; index++;
}
// When you need to have BORROW
else {
out.arr[index] = digitDiff + base;
borrow = 1; // setting borrow = 1
pA++; pB++; index++;
}
}
// When b is exhausted, while a still has element(s)
while (pA < a.len) {
// When there exists a borrow
if (borrow == 1) {
// When borrow is forwarded, as you can't borrow from ZERO
if (a.arr[pA] == 0) {
digitDiff = base - 1;
borrow = 1;
}
// borrow is subtracted
else {
digitDiff = a.arr[pA] - borrow;
borrow = 0; // No more borrows
}
out.arr[index] = digitDiff;
pA++; index++;
}
// No borrow
else {
// just copying a to out
out.arr[index] = a.arr[pA];
borrow = 0;
pA++; index++;
}
}
return trimZeros(out);
}
/**
* Returns Num as a product of Num a and Num b.
* @param a first number
* @param b second number
* @return the product of numbers a and b
*/
public static Num product(Num a, Num b) {
Num out = new Num();
// just getting the scalar product = |a| * |b|
out = out.scalarProduct(a, b);
// Updating the appropriate sign
if (a.isNegative == b.isNegative) {
out.isNegative = false;
} // - * - or + * +
else {
out.isNegative = true;
} // - * + or - * +
return out;
}
/**
* Returns scalar product of two numbers using Karatsuba Algorithm
* @param a the first number
* @param b the second number
* @return the product of a and b
*/
private Num scalarProduct(Num a, Num b) {
Num out = new Num();
// Largest length from two numbers
int n = (a.len < b.len)? b.len : a.len;
// When product a*b = 0 (ZERO), when either of two numbers is ZERO
if ((a.len ==1 && a.arr[0] == 0) || (b.len == 1 && b.arr[0] == 0)) {
out.len = 1;
out.arr = new long[out.len];
out.arr[0] = 0;
return out;
}
// Base Condition: When both numbers are of unit length (have a single digit)
if (a.len == 1 && b.len == 1) {
long prod = a.arr[0] * b.arr[0]; // still in decimal
long carry = prod / base;
// Only single digit is sufficient
if (carry == 0) {
out.len = 1;
out.arr = new long[out.len];
out.arr[0] = prod;
}
// When need two digits for the product
else {
out.len = 2;
out.arr = new long[out.len];
out.arr[0] = prod % base;
out.arr[1] = carry;
}
}
// Karatsuba Algorithm: Fast Integer Multiplication, RT = 0(n^log2 (3))
else {
// a1, b1 being GREATER sub-halves and a2, b2 being LOWER sub-halves
Num a1 = new Num();
Num a2 = new Num(); // a[a2:a1]
Num b1 = new Num();
Num b2 = new Num(); // b[b2:b1]
Num p;
int zeros = 0;
// Initializing appropriate a1[], a2[], b1[] and b2[]
int l2 = n / 2, l1 = n - l2; // NOTE: l1 = {l2+1 OR l2}
a2.len = b2.len = l2;
a1.len = b1.len = l1;
a1.arr = new long[l1]; a2.arr = new long[l2];
b1.arr = new long[l1]; b2.arr = new long[l2];
// When unEqual lengths
if (a.len != b.len) {
zeros = a.len - b.len;
// pad to a
if (zeros < 0) {
// [It's out = p * b]
p = padZeros(a, b.len - a.len);
fragment(p, a1, a2, b, b1, b2); // p to [a1:a2] and b to [b1:b2]
}
// pad to b
else {
// [It's out = a * p]
p = padZeros(b, zeros);
fragment(a, a1, a2, p, b1, b2); // a to [a1:a2] and p to [b1:b2]
}
}
// When Equal length
else {
fragment(a, a1, a2, b, b1, b2); // a to [a1:a2] and b to [b1:b2]
}
// As of Now, we have proper fragments - [a1:a2] and [b1:b2]
// ReC1: r1 = a1*b1
// ReC2: r2 = a2*b2
// ReC3: r3 = (a1+a2)*(b1+b2)
// Recursive Call 1:
Num r1 = new Num();
r1 = scalarProduct(a1, b1);
// Recursive Call 2:
Num r2 = new Num();
r2 = scalarProduct(a2, b2);
// Recursive Call 3:
Num r3 = new Num();
r3 = scalarProduct(unsignedAdd(a1, a2), unsignedAdd(b1, b2));
// CONQUER STEP:
// a * b = shiftZeros(r1,(n/1+n/2)) + r2 + shiftZeros(r3-r2-r1, n/2)
Num sum = unsignedAdd(r1, r2);
Num r4 = normalSubtract(r3, sum);
Num f1 = shiftZeros(r1, (n / 2 + n / 2));
Num f2 = shiftZeros(r4, n / 2);
Num temp = unsignedAdd(f1, r2);
out = unsignedAdd(temp, f2);
}
// Whooosh! thats the correct product :)
return out;
}
/**
* NOTE:
* 1. Though Karatsuba Algorithm RT = 0(n^log 3) sounds great, but it's implementation is
* complicated, as you can see. The divide-and-conquer has a big recursive-overhead when
* the numbers are not of equal length, as we create additional terms and more crossover
* points, and only behaves better when numbers are of equal length.
*
* 2. The O(n^2) is simple and straight-forward. Karatsuba can perform faster than O(n^2) when
* the Num has 10000 digits (arr.length = 10000) or more, which is equivalent to having a number
* of decimal length = 10^(9 * 10000).
*
* 3. It is done for personal satisfaction. If you are aiming for efficiency, you may keep
* the implementation simple with O(n^2) algorithm.
*
* 4. Thus, a complicated 0(n^log 3) doesn't necessarily beat O(n^2) algorithm.
*/
/**
* Karatsuba Algorithm Helper method:
* Fragments a to a1 and a2, and b to b1 and b2.
* Precondition: a and b are of same length n.
* @param a the first number
* @param a1 the higher significant half (length = n - n/2)
* @param a2 the lower significant half (length = n/2)
* @param b the second number
* @param b1 the higher significant half (length = n - n/2)
* @param b2 the lower significant half (length = n/2)
*/
private void fragment(Num a, Num a1, Num a2, Num b, Num b1, Num b2) {
int i = 0;
int n = a.len;
int l2 = n/2;
// Consider a = 12345 = [5,4,3,2,1]. So, l2 = 2.
// a1 = 123 = [3,2,1] and a2 = 45 = [5,4]
for (i=0; i<l2; i++) {
a2.arr[i] = a.arr[i];
b2.arr[i] = b.arr[i];
a1.arr[i] = a.arr[l2 + i];
b1.arr[i] = b.arr[l2 + i];
}
// When n is Odd number
if (n % 2 != 0) {
// a1, b1 would have one more digit than a2, b2 (Case: l1 = l2+1)
a1.arr[i] = a.arr[l2 + i];
b1.arr[i] = b.arr[l2 + i];
}
}
/**
* Pad 'zeros' no of zeros in front of Num a, and
* updating the length return new paddedNum
* @param a the Number required padding
* @param zeros is the no of zeros to be padded
* @return the padded number
*/
private Num padZeros(Num a, int zeros) {
// No padding needed
if (zeros == 0) return a;
Num paddedNum = new Num();
int pLen = a.len + zeros; // NOTE: default number in java is ZERO* ;)
paddedNum.arr = new long[pLen];
int index = 0;
// Copying each element from front until there is one in a.arr
for (long e : a.arr) {
paddedNum.arr[index] = e;
index++;
}
// Appropriate Sign and length of paddedNum
paddedNum.isNegative = a.isNegative;
paddedNum.len = pLen;
return paddedNum;
}
/**
* Shifts digits of Number a with d digits to give a Number
* equivalent to a with 'd' zeros behind.
* @param a The number to be shifted
* @param d the number of zeros to be appended
* @return the output Num = a * 10^d
*/
private Num shiftZeros(Num a, int d) {
Num out = new Num();
out.len = a.len + d; // NOTE: default number in java is ZERO* ;)
out.arr = new long[out.len];
out.isNegative = a.isNegative; // Appropriate sign
int lengthA = a.len;
// Copying digits from a to out
for (int i=0; i<lengthA; i++) {
out.arr[d + i] = a.arr[i]; // assigned to index: d to (a.len + d - 1)
}
return out;
}
/**
* POWER: using Divide-and-Conquer - Recursion
* Returns a^n
* @param a the number as Num
* @param n the exponent in long
* @return a^n
* @throws ArithmeticException on undefined cases
*/
public static Num power(Num a, long n) throws ArithmeticException {
Num out = new Num();
Num one = new Num(1);
Num zero = new Num(0);
Num minusOne = new Num(-1);
// When power is ZERO
if (n == 0) {
if (a.compareTo(zero) == 0) {
throw new ArithmeticException("power(0,0) is Undefined!");
} else {
return one;
}
}
// When power is Negative
if (n < 0) {
if (a.compareTo(zero) == 0)
throw new ArithmeticException("power(0,Negative) is Undefined!");
if (a.isNegative && a.compareTo(one) == 0) {
if (n % 2 == 0) return one; // power(-1, negativeEven)
else return minusOne; // power(-1, negativeOdd)
}
if (a.compareTo(one) == 0) return one; // power(1,anyInteger)
if (a.compareTo(zero) > 0 && a.isNegative) {
if (n % 2 == 0) return zero; // power(negative, negativeEven)
else return minusOne; // power(negative, negativeOdd)
// Referring IDSA Forums. Expected = -1
}
if (a.compareTo(zero) > 0) return zero; // power(positive,negative)
}
// When power is Positive
if (n > 0) {
if (a.compareTo(zero) == 0) return zero; // power(0,positive)
if (a.compareTo(one) == 0 && a.isNegative) { // a = -1
if (n % 2 == 0) return one; // power(-1, positiveEven)
else return minusOne; // power(-1,positiveOdd)
}
if (a.compareTo(one) == 0) return one; // power(1,positive)
// When a is Negative
if (a.compareTo(zero) > 0 && a.isNegative) {
if (n % 2 == 1) out.isNegative = true; // power(negative, positiveEven)
out = out.simplePower(a, n);
return out;
}
// When a is Positive
else return out.simplePower(a, n); // power(positive, positive)
}
return out;
}
/**
* Power Helper method: a != {0, 1, -1} and n is positive
*
* @return returns power(a,n) = a^n
*/
private Num simplePower(Num a, long n) {
if (n == 0) return new Num(1); // a^0 = 1
if (n == 1) return a; // a^1
Num halfPower = simplePower(a, n/2); // saving (4 - 1) recursive calls
// When n is Positive and EVEN
if (n % 2 == 0)
return product(halfPower, halfPower);
// When n is Positive and ODD
else
return product(a, product(halfPower, halfPower));
}
/**
* Division using Binary Search method
* @param a the dividend
* @param b the divisor
* @return the integer quotient
* @throws ArithmeticException when exception arise.
*/
public static Num divide(Num a, Num b) throws ArithmeticException {
Num out = new Num();
Num zero = new Num(0);
Num one = new Num(1);
Num minusOne = new Num(-1);
Num two = new Num(2);
// Division by ZERO
if (b.compareTo(zero) == 0)
throw new ArithmeticException("Division by ZERO.");
// Numerator is ZERO
if (a.compareTo(zero) == 0)
return zero;
// Denominator is one/ minusOne
if (b.compareTo(one) == 0) {
// assigning correct sign to 'out'
out.isNegative = (b.isNegative)? !a.isNegative: a.isNegative;
out.len = a.len;
out.arr = new long[out.len]; // Copying a to out
int i=0;
for (long e : a.arr) { out.arr[i++] = e; }
return out;
}
// When division is by 2
if (b.compareTo(two) == 0) {
out.isNegative = (b.isNegative) ? !a.isNegative : a.isNegative;
out = a.by2();
return out;
}
// |a| < |b|, causing division either ZERO or minusOne
if (a.compareTo(b) < 0) {
if (a.isNegative == b.isNegative) return zero;
else return minusOne;
}
// |a| == |b|
if (a.compareTo(b) == 0) {
if (a.isNegative == b.isNegative) return one;
else return minusOne;
}
// Binary Search begins
Num low = new Num(1);
Num high = new Num();
// Copying a to high
// high.isNegative = a.isNegative; // DONT NEED THIS*
high.len = a.len;
high.arr = new long[high.len];
int i = 0;
for (long e : a.arr) { high.arr[i++] = e; }
// mid = (low + high) / 2.
Num mid = new Num();
while (low.compareTo(high) < 0) {
Num sum = out.unsignedAdd(low, high);
mid = sum.by2();
if (mid.compareTo(low) == 0)
break; // When mid = low
Num prod = out.scalarProduct(mid, b);
if (prod.compareTo(a) == 0)
break; // When mid*b = a
else if (prod.compareTo(a) > 0)
high = mid;
else
low = mid;
}
// When a, b has different signs
if (a.isNegative != b.isNegative)
mid.isNegative = true;
return mid;
}
/**
* Returns modulo: a mod b
* @param a the first operand
* @param b the second operand
* @return the modulo
* @throws ArithmeticException
*/
public static Num mod(Num a, Num b) throws ArithmeticException {
Num zero = new Num(0);
Num one = new Num(1);
// When Undefined modulo operation
if (a.isNegative || b.isNegative || b.compareTo(zero) == 0)
throw new ArithmeticException("Undefined mod!");
// NOTE: b wouldn't be minusOne
if (b.compareTo(one) == 0)
return a;
Num quotient = divide(a, b);
Num product = product(quotient, b);
Num remainder = subtract(a, product);
return remainder;
}
/**
* Returns square root of a Num using Binary Search
* @param a the number
* @return the square root
* @throws ArithmeticException for undefined numbers
*/
public static Num squareRoot(Num a) throws ArithmeticException {
Num zero = new Num(0);
Num one = new Num(1);
// When a is NEGATIVE
if (a.isNegative)
throw new ArithmeticException("squareRoot(Negatives) is undefined!");
if (a.compareTo(zero) == 0)
return zero; // When a is ZERO
if (a.compareTo(one) == 0)
return zero; // When a is ONE
Num low = new Num(0);
Num high = new Num();
// Copying a to high
high.isNegative = a.isNegative;
high.len = a.len;
high.arr = new long[high.len];
int i = 0;
for (long e : a.arr) { high.arr[i++] = e; }
Num mid = new Num();
Num sum = new Num(0);
// Quite similar to divide
while (low.compareTo(high) < 0) {
sum = add(low, high);
mid = sum.by2();
if (low.compareTo(mid) == 0)
return mid;
Num prod = product(mid, mid);
if (prod.compareTo(a) == 0)
return mid;
else if (prod.compareTo(a) < 0)
low = mid;
else
high = mid;
}
return mid;
}
/**
* Compare "this" to "other": return +1 if this is greater, 0 if equal, -1 otherwise.
* NOTE: Compares ONLY Magnitude of each number, NOT according to the sign.
* @param other the other number
*/
public int compareTo(Num other) {
// When lengths are unequal
if (this.len < other.len) return -1;
if (other.len < this.len) return 1;
// When same length, look for greatest highest significant digit
else {
int index = this.len - 1;
while (index > -1) {
// Inequality check: this < other
if (this.arr[index] < other.arr[index])
return -1;
// Inequality check: other < this
if (other.arr[index] < this.arr[index])
return 1;
index--;
}
}
// When Equal Numbers
return 0;
}
/**
* Output using the format "base: elements of list"
* For example, if base = 100, and the number stored corresponds to -10965,
* then the output is "100: - [65, 9, 1]"
*/
public void printList() {
System.out.print(base()+": ");
if (this.isNegative) System.out.print("- ");
System.out.print("[");
int i=0;
while (i<this.len) {
if (i == this.len - 1) System.out.print(this.arr[i]);
else System.out.print(this.arr[i]+", ");
i++;
}
System.out.print("]");
System.out.println();
}
/**
* Returns this number in DECIMAL
*/
public String toString() {
// To get the number in base()
this.arr = convertToOriginalBase();
this.len = this.arr.length;
StringBuilder sb = new StringBuilder();
long temp, countDigits = 0, maxNo = base - 1, append0 = 0;
if (isNegative) sb.append("-");
// Append zeros if required to each 'digit'
for (int i = len-1; i >= 0; i--) {
countDigits = 0;
if (i == len - 1) {
sb.append(arr[i]);
continue;
}
// Counting no of digits(base=10) in each digit(our base)
temp = arr[i];
while (temp < maxNo && temp > 0) {
temp = temp / 10;
countDigits++;
}
append0 = digits - countDigits;
// Actually appending the zeros
while (append0 > 0) {
sb.append("0");
append0--;
}
sb.append(arr[i]);
}
return sb.toString();
}
// Returns base
public long base() {
return base;
}