-
Notifications
You must be signed in to change notification settings - Fork 3
/
numbers.js
1880 lines (1542 loc) · 53 KB
/
numbers.js
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
var JSBigInt = (function () {
"use strict";
/*
Class: BigInteger
An arbitrarily-large integer.
<BigInteger> objects should be considered immutable. None of the "built-in"
methods modify *this* or their arguments. All properties should be
considered private.
All the methods of <BigInteger> instances can be called "statically". The
static versions are convenient if you don't already have a <BigInteger>
object.
As an example, these calls are equivalent.
> BigInteger(4).multiply(5); // returns BigInteger(20);
> BigInteger.multiply(4, 5); // returns BigInteger(20);
> var a = 42;
> var a = BigInteger.toJSValue("0b101010"); // Not completely useless...
*/
var CONSTRUCT = {}; // Unique token to call "private" version of constructor
/*
Constructor: BigInteger()
Convert a value to a <BigInteger>.
Although <BigInteger()> is the constructor for <BigInteger> objects, it is
best not to call it as a constructor. If *n* is a <BigInteger> object, it is
simply returned as-is. Otherwise, <BigInteger()> is equivalent to <parse>
without a radix argument.
> var n0 = BigInteger(); // Same as <BigInteger.ZERO>
> var n1 = BigInteger("123"); // Create a new <BigInteger> with value 123
> var n2 = BigInteger(123); // Create a new <BigInteger> with value 123
> var n3 = BigInteger(n2); // Return n2, unchanged
The constructor form only takes an array and a sign. *n* must be an
array of numbers in little-endian order, where each digit is between 0
and BigInteger.base. The second parameter sets the sign: -1 for
negative, +1 for positive, or 0 for zero. The array is *not copied and
may be modified*. If the array contains only zeros, the sign parameter
is ignored and is forced to zero.
> new BigInteger([5], -1): create a new BigInteger with value -5
Parameters:
n - Value to convert to a <BigInteger>.
Returns:
A <BigInteger> value.
See Also:
<parse>, <BigInteger>
*/
function BigInteger(n, s, token) {
if (token !== CONSTRUCT) {
if (n instanceof BigInteger) {
return n;
} else if (typeof n === "undefined") {
return ZERO;
}
return BigInteger.parse(n);
}
n = n || []; // Provide the nullary constructor for subclasses.
while (n.length && !n[n.length - 1]) {
--n.length;
}
this._d = n;
this._s = n.length ? (s || 1) : 0;
}
BigInteger._construct = function (n, s) {
return new BigInteger(n, s, CONSTRUCT);
};
// Base-10 speedup hacks in parse, toString, exp10 and log functions
// require base to be a power of 10. 10^7 is the largest such power
// that won't cause a precision loss when digits are multiplied.
var BigInteger_base = 10000000;
var BigInteger_base_log10 = 7;
BigInteger.base = BigInteger_base;
BigInteger.base_log10 = BigInteger_base_log10;
var ZERO = new BigInteger([], 0, CONSTRUCT);
// Constant: ZERO
// <BigInteger> 0.
BigInteger.ZERO = ZERO;
var ONE = new BigInteger([1], 1, CONSTRUCT);
// Constant: ONE
// <BigInteger> 1.
BigInteger.ONE = ONE;
var M_ONE = new BigInteger(ONE._d, -1, CONSTRUCT);
// Constant: M_ONE
// <BigInteger> -1.
BigInteger.M_ONE = M_ONE;
// Constant: _0
// Shortcut for <ZERO>.
BigInteger._0 = ZERO;
// Constant: _1
// Shortcut for <ONE>.
BigInteger._1 = ONE;
/*
Constant: small
Array of <BigIntegers> from 0 to 36.
These are used internally for parsing, but useful when you need a "small"
<BigInteger>.
See Also:
<ZERO>, <ONE>, <_0>, <_1>
*/
BigInteger.small = [
ZERO,
ONE,
/* Assuming BigInteger_base > 36 */
new BigInteger([2], 1, CONSTRUCT),
new BigInteger([3], 1, CONSTRUCT),
new BigInteger([4], 1, CONSTRUCT),
new BigInteger([5], 1, CONSTRUCT),
new BigInteger([6], 1, CONSTRUCT),
new BigInteger([7], 1, CONSTRUCT),
new BigInteger([8], 1, CONSTRUCT),
new BigInteger([9], 1, CONSTRUCT),
new BigInteger([10], 1, CONSTRUCT),
new BigInteger([11], 1, CONSTRUCT),
new BigInteger([12], 1, CONSTRUCT),
new BigInteger([13], 1, CONSTRUCT),
new BigInteger([14], 1, CONSTRUCT),
new BigInteger([15], 1, CONSTRUCT),
new BigInteger([16], 1, CONSTRUCT),
new BigInteger([17], 1, CONSTRUCT),
new BigInteger([18], 1, CONSTRUCT),
new BigInteger([19], 1, CONSTRUCT),
new BigInteger([20], 1, CONSTRUCT),
new BigInteger([21], 1, CONSTRUCT),
new BigInteger([22], 1, CONSTRUCT),
new BigInteger([23], 1, CONSTRUCT),
new BigInteger([24], 1, CONSTRUCT),
new BigInteger([25], 1, CONSTRUCT),
new BigInteger([26], 1, CONSTRUCT),
new BigInteger([27], 1, CONSTRUCT),
new BigInteger([28], 1, CONSTRUCT),
new BigInteger([29], 1, CONSTRUCT),
new BigInteger([30], 1, CONSTRUCT),
new BigInteger([31], 1, CONSTRUCT),
new BigInteger([32], 1, CONSTRUCT),
new BigInteger([33], 1, CONSTRUCT),
new BigInteger([34], 1, CONSTRUCT),
new BigInteger([35], 1, CONSTRUCT),
new BigInteger([36], 1, CONSTRUCT)
];
// Used for parsing/radix conversion
BigInteger.digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
/*
Method: toString
Convert a <BigInteger> to a string.
When *base* is greater than 10, letters are upper case.
Parameters:
base - Optional base to represent the number in (default is base 10).
Must be between 2 and 36 inclusive, or an Error will be thrown.
Returns:
The string representation of the <BigInteger>.
*/
BigInteger.prototype.toString = function (base) {
base = +base || 10;
if (base < 2 || base > 36) {
throw new Error("illegal radix " + base + ".");
}
if (this._s === 0) {
return "0";
}
if (base === 10) {
var str = this._s < 0 ? "-" : "";
str += this._d[this._d.length - 1].toString();
for (var i = this._d.length - 2; i >= 0; i--) {
var group = this._d[i].toString();
while (group.length < BigInteger_base_log10) group = '0' + group;
str += group;
}
return str;
} else {
var numerals = BigInteger.digits;
base = BigInteger.small[base];
var sign = this._s;
var n = this.abs();
var digits = [];
var digit;
while (n._s !== 0) {
var divmod = n.divRem(base);
n = divmod[0];
digit = divmod[1];
// TODO: This could be changed to unshift instead of reversing at the end.
// Benchmark both to compare speeds.
digits.push(numerals[digit.valueOf()]);
}
return (sign < 0 ? "-" : "") + digits.reverse().join("");
}
};
// Verify strings for parsing
BigInteger.radixRegex = [
/^$/,
/^$/,
/^[01]*$/,
/^[012]*$/,
/^[0-3]*$/,
/^[0-4]*$/,
/^[0-5]*$/,
/^[0-6]*$/,
/^[0-7]*$/,
/^[0-8]*$/,
/^[0-9]*$/,
/^[0-9aA]*$/,
/^[0-9abAB]*$/,
/^[0-9abcABC]*$/,
/^[0-9a-dA-D]*$/,
/^[0-9a-eA-E]*$/,
/^[0-9a-fA-F]*$/,
/^[0-9a-gA-G]*$/,
/^[0-9a-hA-H]*$/,
/^[0-9a-iA-I]*$/,
/^[0-9a-jA-J]*$/,
/^[0-9a-kA-K]*$/,
/^[0-9a-lA-L]*$/,
/^[0-9a-mA-M]*$/,
/^[0-9a-nA-N]*$/,
/^[0-9a-oA-O]*$/,
/^[0-9a-pA-P]*$/,
/^[0-9a-qA-Q]*$/,
/^[0-9a-rA-R]*$/,
/^[0-9a-sA-S]*$/,
/^[0-9a-tA-T]*$/,
/^[0-9a-uA-U]*$/,
/^[0-9a-vA-V]*$/,
/^[0-9a-wA-W]*$/,
/^[0-9a-xA-X]*$/,
/^[0-9a-yA-Y]*$/,
/^[0-9a-zA-Z]*$/
];
/*
Function: parse
Parse a string into a <BigInteger>.
*base* is optional but, if provided, must be from 2 to 36 inclusive. If
*base* is not provided, it will be guessed based on the leading characters
of *s* as follows:
- "0x" or "0X": *base* = 16
- "0c" or "0C": *base* = 8
- "0b" or "0B": *base* = 2
- else: *base* = 10
If no base is provided, or *base* is 10, the number can be in exponential
form. For example, these are all valid:
> BigInteger.parse("1e9"); // Same as "1000000000"
> BigInteger.parse("1.234*10^3"); // Same as 1234
> BigInteger.parse("56789 * 10 ** -2"); // Same as 567
If any characters fall outside the range defined by the radix, an exception
will be thrown.
Parameters:
s - The string to parse.
base - Optional radix (default is to guess based on *s*).
Returns:
a <BigInteger> instance.
*/
BigInteger.parse = function (s, base) {
// Expands a number in exponential form to decimal form.
// expandExponential("-13.441*10^5") === "1344100";
// expandExponential("1.12300e-1") === "0.112300";
// expandExponential(1000000000000000000000000000000) === "1000000000000000000000000000000";
function expandExponential(str) {
str = str.replace(/\s*[*xX]\s*10\s*(\^|\*\*)\s*/, "e");
return str.replace(/^([+\-])?(\d+)\.?(\d*)[eE]([+\-]?\d+)$/, function (x, s, n, f, c) {
c = +c;
var l = c < 0;
var i = n.length + c;
x = (l ? n : f).length;
c = ((c = Math.abs(c)) >= x ? c - x + l : 0);
var z = (new Array(c + 1)).join("0");
var r = n + f;
return (s || "") + (l ? r = z + r : r += z).substr(0, i += l ? z.length : 0) + (i < r.length ? "." + r.substr(i) : "");
});
}
s = s.toString();
if (typeof base === "undefined" || +base === 10) {
s = expandExponential(s);
}
var prefixRE;
if (typeof base === "undefined") {
prefixRE = '0[xcb]';
} else if (base == 16) {
prefixRE = '0x';
} else if (base == 8) {
prefixRE = '0c';
} else if (base == 2) {
prefixRE = '0b';
} else {
prefixRE = '';
}
var parts = new RegExp('^([+\\-]?)(' + prefixRE + ')?([0-9a-z]*)(?:\\.\\d*)?$', 'i').exec(s);
if (parts) {
var sign = parts[1] || "+";
var baseSection = parts[2] || "";
var digits = parts[3] || "";
if (typeof base === "undefined") {
// Guess base
if (baseSection === "0x" || baseSection === "0X") { // Hex
base = 16;
} else if (baseSection === "0c" || baseSection === "0C") { // Octal
base = 8;
} else if (baseSection === "0b" || baseSection === "0B") { // Binary
base = 2;
} else {
base = 10;
}
} else if (base < 2 || base > 36) {
throw new Error("Illegal radix " + base + ".");
}
base = +base;
// Check for digits outside the range
if (!(BigInteger.radixRegex[base].test(digits))) {
throw new Error("Bad digit for radix " + base);
}
// Strip leading zeros, and convert to array
digits = digits.replace(/^0+/, "").split("");
if (digits.length === 0) {
return ZERO;
}
// Get the sign (we know it's not zero)
sign = (sign === "-") ? -1 : 1;
// Optimize 10
if (base == 10) {
var d = [];
while (digits.length >= BigInteger_base_log10) {
d.push(parseInt(digits.splice(digits.length - BigInteger.base_log10, BigInteger.base_log10).join(''), 10));
}
d.push(parseInt(digits.join(''), 10));
return new BigInteger(d, sign, CONSTRUCT);
}
// Do the conversion
var d = ZERO;
base = BigInteger.small[base];
var small = BigInteger.small;
for (var i = 0; i < digits.length; i++) {
d = d.multiply(base).add(small[parseInt(digits[i], 36)]);
}
return new BigInteger(d._d, sign, CONSTRUCT);
} else {
throw new Error("Invalid BigInteger format: " + s);
}
};
/*
Function: add
Add two <BigIntegers>.
Parameters:
n - The number to add to *this*. Will be converted to a <BigInteger>.
Returns:
The numbers added together.
See Also:
<subtract>, <multiply>, <quotient>, <next>
*/
BigInteger.prototype.add = function (n) {
if (this._s === 0) {
return BigInteger(n);
}
n = BigInteger(n);
if (n._s === 0) {
return this;
}
if (this._s !== n._s) {
n = n.negate();
return this.subtract(n);
}
var a = this._d;
var b = n._d;
var al = a.length;
var bl = b.length;
var sum = new Array(Math.max(al, bl) + 1);
var size = Math.min(al, bl);
var carry = 0;
var digit;
for (var i = 0; i < size; i++) {
digit = a[i] + b[i] + carry;
sum[i] = digit % BigInteger_base;
carry = (digit / BigInteger_base) | 0;
}
if (bl > al) {
a = b;
al = bl;
}
for (i = size; carry && i < al; i++) {
digit = a[i] + carry;
sum[i] = digit % BigInteger_base;
carry = (digit / BigInteger_base) | 0;
}
if (carry) {
sum[i] = carry;
}
for (; i < al; i++) {
sum[i] = a[i];
}
return new BigInteger(sum, this._s, CONSTRUCT);
};
/*
Function: negate
Get the additive inverse of a <BigInteger>.
Returns:
A <BigInteger> with the same magnatude, but with the opposite sign.
See Also:
<abs>
*/
BigInteger.prototype.negate = function () {
return new BigInteger(this._d, (-this._s) | 0, CONSTRUCT);
};
/*
Function: abs
Get the absolute value of a <BigInteger>.
Returns:
A <BigInteger> with the same magnatude, but always positive (or zero).
See Also:
<negate>
*/
BigInteger.prototype.abs = function () {
return (this._s < 0) ? this.negate() : this;
};
/*
Function: subtract
Subtract two <BigIntegers>.
Parameters:
n - The number to subtract from *this*. Will be converted to a <BigInteger>.
Returns:
The *n* subtracted from *this*.
See Also:
<add>, <multiply>, <quotient>, <prev>
*/
BigInteger.prototype.subtract = function (n) {
if (this._s === 0) {
return BigInteger(n).negate();
}
n = BigInteger(n);
if (n._s === 0) {
return this;
}
if (this._s !== n._s) {
n = n.negate();
return this.add(n);
}
var m = this;
// negative - negative => -|a| - -|b| => -|a| + |b| => |b| - |a|
if (this._s < 0) {
m = new BigInteger(n._d, 1, CONSTRUCT);
n = new BigInteger(this._d, 1, CONSTRUCT);
}
// Both are positive => a - b
var sign = m.compareAbs(n);
if (sign === 0) {
return ZERO;
} else if (sign < 0) {
// swap m and n
var t = n;
n = m;
m = t;
}
// a > b
var a = m._d;
var b = n._d;
var al = a.length;
var bl = b.length;
var diff = new Array(al); // al >= bl since a > b
var borrow = 0;
var i;
var digit;
for (i = 0; i < bl; i++) {
digit = a[i] - borrow - b[i];
if (digit < 0) {
digit += BigInteger_base;
borrow = 1;
} else {
borrow = 0;
}
diff[i] = digit;
}
for (i = bl; i < al; i++) {
digit = a[i] - borrow;
if (digit < 0) {
digit += BigInteger_base;
} else {
diff[i++] = digit;
break;
}
diff[i] = digit;
}
for (; i < al; i++) {
diff[i] = a[i];
}
return new BigInteger(diff, sign, CONSTRUCT);
};
(function () {
function addOne(n, sign) {
var a = n._d;
var sum = a.slice();
var carry = true;
var i = 0;
while (true) {
var digit = (a[i] || 0) + 1;
sum[i] = digit % BigInteger_base;
if (digit <= BigInteger_base - 1) {
break;
}
++i;
}
return new BigInteger(sum, sign, CONSTRUCT);
}
function subtractOne(n, sign) {
var a = n._d;
var sum = a.slice();
var borrow = true;
var i = 0;
while (true) {
var digit = (a[i] || 0) - 1;
if (digit < 0) {
sum[i] = digit + BigInteger_base;
} else {
sum[i] = digit;
break;
}
++i;
}
return new BigInteger(sum, sign, CONSTRUCT);
}
/*
Function: next
Get the next <BigInteger> (add one).
Returns:
*this* + 1.
See Also:
<add>, <prev>
*/
BigInteger.prototype.next = function () {
switch (this._s) {
case 0:
return ONE;
case -1:
return subtractOne(this, -1);
// case 1:
default:
return addOne(this, 1);
}
};
/*
Function: prev
Get the previous <BigInteger> (subtract one).
Returns:
*this* - 1.
See Also:
<next>, <subtract>
*/
BigInteger.prototype.prev = function () {
switch (this._s) {
case 0:
return M_ONE;
case -1:
return addOne(this, -1);
// case 1:
default:
return subtractOne(this, 1);
}
};
})();
/*
Function: compareAbs
Compare the absolute value of two <BigIntegers>.
Calling <compareAbs> is faster than calling <abs> twice, then <compare>.
Parameters:
n - The number to compare to *this*. Will be converted to a <BigInteger>.
Returns:
-1, 0, or +1 if *|this|* is less than, equal to, or greater than *|n|*.
See Also:
<compare>, <abs>
*/
BigInteger.prototype.compareAbs = function (n) {
if (this === n) {
return 0;
}
if (!(n instanceof BigInteger)) {
if (!isFinite(n)) {
return (isNaN(n) ? n : -1);
}
n = BigInteger(n);
}
if (this._s === 0) {
return (n._s !== 0) ? -1 : 0;
}
if (n._s === 0) {
return 1;
}
var l = this._d.length;
var nl = n._d.length;
if (l < nl) {
return -1;
} else if (l > nl) {
return 1;
}
var a = this._d;
var b = n._d;
for (var i = l - 1; i >= 0; i--) {
if (a[i] !== b[i]) {
return a[i] < b[i] ? -1 : 1;
}
}
return 0;
};
/*
Function: compare
Compare two <BigIntegers>.
Parameters:
n - The number to compare to *this*. Will be converted to a <BigInteger>.
Returns:
-1, 0, or +1 if *this* is less than, equal to, or greater than *n*.
See Also:
<compareAbs>, <isPositive>, <isNegative>, <isUnit>
*/
BigInteger.prototype.compare = function (n) {
if (this === n) {
return 0;
}
n = BigInteger(n);
if (this._s === 0) {
return -n._s;
}
if (this._s === n._s) { // both positive or both negative
var cmp = this.compareAbs(n);
return cmp * this._s;
} else {
return this._s;
}
};
/*
Function: isUnit
Return true iff *this* is either 1 or -1.
Returns:
true if *this* compares equal to <BigInteger.ONE> or <BigInteger.M_ONE>.
See Also:
<isZero>, <isNegative>, <isPositive>, <compareAbs>, <compare>,
<BigInteger.ONE>, <BigInteger.M_ONE>
*/
BigInteger.prototype.isUnit = function () {
return this === ONE ||
this === M_ONE ||
(this._d.length === 1 && this._d[0] === 1);
};
/*
Function: multiply
Multiply two <BigIntegers>.
Parameters:
n - The number to multiply *this* by. Will be converted to a
<BigInteger>.
Returns:
The numbers multiplied together.
See Also:
<add>, <subtract>, <quotient>, <square>
*/
BigInteger.prototype.multiply = function (n) {
// TODO: Consider adding Karatsuba multiplication for large numbers
if (this._s === 0) {
return ZERO;
}
n = BigInteger(n);
if (n._s === 0) {
return ZERO;
}
if (this.isUnit()) {
if (this._s < 0) {
return n.negate();
}
return n;
}
if (n.isUnit()) {
if (n._s < 0) {
return this.negate();
}
return this;
}
if (this === n) {
return this.square();
}
var r = (this._d.length >= n._d.length);
var a = (r ? this : n)._d; // a will be longer than b
var b = (r ? n : this)._d;
var al = a.length;
var bl = b.length;
var pl = al + bl;
var partial = new Array(pl);
var i;
for (i = 0; i < pl; i++) {
partial[i] = 0;
}
for (i = 0; i < bl; i++) {
var carry = 0;
var bi = b[i];
var jlimit = al + i;
var digit;
for (var j = i; j < jlimit; j++) {
digit = partial[j] + bi * a[j - i] + carry;
carry = (digit / BigInteger_base) | 0;
partial[j] = (digit % BigInteger_base) | 0;
}
if (carry) {
digit = partial[j] + carry;
carry = (digit / BigInteger_base) | 0;
partial[j] = digit % BigInteger_base;
}
}
return new BigInteger(partial, this._s * n._s, CONSTRUCT);
};
// Multiply a BigInteger by a single-digit native number
// Assumes that this and n are >= 0
// This is not really intended to be used outside the library itself
BigInteger.prototype.multiplySingleDigit = function (n) {
if (n === 0 || this._s === 0) {
return ZERO;
}
if (n === 1) {
return this;
}
var digit;
if (this._d.length === 1) {
digit = this._d[0] * n;
if (digit >= BigInteger_base) {
return new BigInteger([(digit % BigInteger_base) | 0,
(digit / BigInteger_base) | 0], 1, CONSTRUCT);
}
return new BigInteger([digit], 1, CONSTRUCT);
}
if (n === 2) {
return this.add(this);
}
if (this.isUnit()) {
return new BigInteger([n], 1, CONSTRUCT);
}
var a = this._d;
var al = a.length;
var pl = al + 1;
var partial = new Array(pl);
for (var i = 0; i < pl; i++) {
partial[i] = 0;
}
var carry = 0;
for (var j = 0; j < al; j++) {
digit = n * a[j] + carry;
carry = (digit / BigInteger_base) | 0;
partial[j] = (digit % BigInteger_base) | 0;
}
if (carry) {
partial[j] = carry;
}
return new BigInteger(partial, 1, CONSTRUCT);
};
/*
Function: square
Multiply a <BigInteger> by itself.
This is slightly faster than regular multiplication, since it removes the
duplicated multiplcations.
Returns:
> this.multiply(this)
See Also:
<multiply>
*/
BigInteger.prototype.square = function () {
// Normally, squaring a 10-digit number would take 100 multiplications.
// Of these 10 are unique diagonals, of the remaining 90 (100-10), 45 are repeated.
// This procedure saves (N*(N-1))/2 multiplications, (e.g., 45 of 100 multiplies).
// Based on code by Gary Darby, Intellitech Systems Inc., www.DelphiForFun.org
if (this._s === 0) {
return ZERO;
}
if (this.isUnit()) {
return ONE;
}
var digits = this._d;
var length = digits.length;
var imult1 = new Array(length + length + 1);
var product, carry, k;
var i;
// Calculate diagonal
for (i = 0; i < length; i++) {
k = i * 2;
product = digits[i] * digits[i];
carry = (product / BigInteger_base) | 0;
imult1[k] = product % BigInteger_base;
imult1[k + 1] = carry;
}
// Calculate repeating part
for (i = 0; i < length; i++) {
carry = 0;
k = i * 2 + 1;
for (var j = i + 1; j < length; j++, k++) {
product = digits[j] * digits[i] * 2 + imult1[k] + carry;
carry = (product / BigInteger_base) | 0;
imult1[k] = product % BigInteger_base;
}
k = length + i;
var digit = carry + imult1[k];
carry = (digit / BigInteger_base) | 0;
imult1[k] = digit % BigInteger_base;
imult1[k + 1] += carry;
}
return new BigInteger(imult1, 1, CONSTRUCT);
};
/*
Function: quotient
Divide two <BigIntegers> and truncate towards zero.
<quotient> throws an exception if *n* is zero.
Parameters:
n - The number to divide *this* by. Will be converted to a <BigInteger>.
Returns:
The *this* / *n*, truncated to an integer.
See Also:
<add>, <subtract>, <multiply>, <divRem>, <remainder>
*/
BigInteger.prototype.quotient = function (n) {
return this.divRem(n)[0];
};
/*
Function: divide
Deprecated synonym for <quotient>.
*/
BigInteger.prototype.divide = BigInteger.prototype.quotient;
/*
Function: remainder
Calculate the remainder of two <BigIntegers>.
<remainder> throws an exception if *n* is zero.
Parameters:
n - The remainder after *this* is divided *this* by *n*. Will be
converted to a <BigInteger>.
Returns:
*this* % *n*.