forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbigint.rs
2902 lines (2575 loc) · 87.4 KB
/
bigint.rs
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
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A Big integer (signed version: `BigInt`, unsigned version: `BigUint`).
//!
//! A `BigUint` is represented as an array of `BigDigit`s.
//! A `BigInt` is a combination of `BigUint` and `Sign`.
//!
//! Common numerical operations are overloaded, so we can treat them
//! the same way we treat other numbers.
//!
//! ## Example
//!
//! ```rust
//! use num::bigint::BigUint;
//! use std::num::{Zero, One};
//! use std::mem::replace;
//!
//! // Calculate large fibonacci numbers.
//! fn fib(n: uint) -> BigUint {
//! let mut f0: BigUint = Zero::zero();
//! let mut f1: BigUint = One::one();
//! for _ in range(0, n) {
//! let f2 = f0 + f1;
//! // This is a low cost way of swapping f0 with f1 and f1 with f2.
//! f0 = replace(&mut f1, f2);
//! }
//! f0
//! }
//!
//! // This is a very large number.
//! println!("fib(1000) = {}", fib(1000));
//! ```
//!
//! It's easy to generate large random numbers:
//!
//! ```rust
//! use num::bigint::{ToBigInt, RandBigInt};
//! use std::rand;
//!
//! let mut rng = rand::task_rng();
//! let a = rng.gen_bigint(1000u);
//!
//! let low = -10000i.to_bigint().unwrap();
//! let high = 10000i.to_bigint().unwrap();
//! let b = rng.gen_bigint_range(&low, &high);
//!
//! // Probably an even larger number.
//! println!("{}", a * b);
//! ```
use Integer;
use rand::Rng;
use std::{cmp, fmt};
use std::default::Default;
use std::from_str::FromStr;
use std::num::CheckedDiv;
use std::num::{ToPrimitive, FromPrimitive};
use std::num::{Zero, One, ToStrRadix, FromStrRadix};
use std::string::String;
use std::{uint, i64, u64};
/// A `BigDigit` is a `BigUint`'s composing element.
pub type BigDigit = u32;
/// A `DoubleBigDigit` is the internal type used to do the computations. Its
/// size is the double of the size of `BigDigit`.
pub type DoubleBigDigit = u64;
pub static ZERO_BIG_DIGIT: BigDigit = 0;
static ZERO_VEC: [BigDigit, ..1] = [ZERO_BIG_DIGIT];
pub mod BigDigit {
use super::BigDigit;
use super::DoubleBigDigit;
// `DoubleBigDigit` size dependent
pub static bits: uint = 32;
pub static base: DoubleBigDigit = 1 << bits;
static lo_mask: DoubleBigDigit = (-1 as DoubleBigDigit) >> bits;
#[inline]
fn get_hi(n: DoubleBigDigit) -> BigDigit { (n >> bits) as BigDigit }
#[inline]
fn get_lo(n: DoubleBigDigit) -> BigDigit { (n & lo_mask) as BigDigit }
/// Split one `DoubleBigDigit` into two `BigDigit`s.
#[inline]
pub fn from_doublebigdigit(n: DoubleBigDigit) -> (BigDigit, BigDigit) {
(get_hi(n), get_lo(n))
}
/// Join two `BigDigit`s into one `DoubleBigDigit`
#[inline]
pub fn to_doublebigdigit(hi: BigDigit, lo: BigDigit) -> DoubleBigDigit {
(lo as DoubleBigDigit) | ((hi as DoubleBigDigit) << bits)
}
}
/// A big unsigned integer type.
///
/// A `BigUint`-typed value `BigUint { data: vec!(a, b, c) }` represents a number
/// `(a + b * BigDigit::base + c * BigDigit::base^2)`.
#[deriving(Clone)]
pub struct BigUint {
data: Vec<BigDigit>
}
impl PartialEq for BigUint {
#[inline]
fn eq(&self, other: &BigUint) -> bool {
match self.cmp(other) { Equal => true, _ => false }
}
}
impl Eq for BigUint {}
impl PartialOrd for BigUint {
#[inline]
fn partial_cmp(&self, other: &BigUint) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for BigUint {
#[inline]
fn cmp(&self, other: &BigUint) -> Ordering {
let (s_len, o_len) = (self.data.len(), other.data.len());
if s_len < o_len { return Less; }
if s_len > o_len { return Greater; }
for (&self_i, &other_i) in self.data.iter().rev().zip(other.data.iter().rev()) {
if self_i < other_i { return Less; }
if self_i > other_i { return Greater; }
}
return Equal;
}
}
impl Default for BigUint {
#[inline]
fn default() -> BigUint { Zero::zero() }
}
impl fmt::Show for BigUint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.to_str_radix(10))
}
}
impl FromStr for BigUint {
#[inline]
fn from_str(s: &str) -> Option<BigUint> {
FromStrRadix::from_str_radix(s, 10)
}
}
impl Num for BigUint {}
impl BitAnd<BigUint, BigUint> for BigUint {
fn bitand(&self, other: &BigUint) -> BigUint {
BigUint::new(self.data.iter().zip(other.data.iter()).map(|(ai, bi)| *ai & *bi).collect())
}
}
impl BitOr<BigUint, BigUint> for BigUint {
fn bitor(&self, other: &BigUint) -> BigUint {
let zeros = ZERO_VEC.iter().cycle();
let (a, b) = if self.data.len() > other.data.len() { (self, other) } else { (other, self) };
let ored = a.data.iter().zip(b.data.iter().chain(zeros)).map(
|(ai, bi)| *ai | *bi
).collect();
return BigUint::new(ored);
}
}
impl BitXor<BigUint, BigUint> for BigUint {
fn bitxor(&self, other: &BigUint) -> BigUint {
let zeros = ZERO_VEC.iter().cycle();
let (a, b) = if self.data.len() > other.data.len() { (self, other) } else { (other, self) };
let xored = a.data.iter().zip(b.data.iter().chain(zeros)).map(
|(ai, bi)| *ai ^ *bi
).collect();
return BigUint::new(xored);
}
}
impl Shl<uint, BigUint> for BigUint {
#[inline]
fn shl(&self, rhs: &uint) -> BigUint {
let n_unit = *rhs / BigDigit::bits;
let n_bits = *rhs % BigDigit::bits;
return self.shl_unit(n_unit).shl_bits(n_bits);
}
}
impl Shr<uint, BigUint> for BigUint {
#[inline]
fn shr(&self, rhs: &uint) -> BigUint {
let n_unit = *rhs / BigDigit::bits;
let n_bits = *rhs % BigDigit::bits;
return self.shr_unit(n_unit).shr_bits(n_bits);
}
}
impl Zero for BigUint {
#[inline]
fn zero() -> BigUint { BigUint::new(Vec::new()) }
#[inline]
fn is_zero(&self) -> bool { self.data.is_empty() }
}
impl One for BigUint {
#[inline]
fn one() -> BigUint { BigUint::new(vec!(1)) }
}
impl Unsigned for BigUint {}
impl Add<BigUint, BigUint> for BigUint {
fn add(&self, other: &BigUint) -> BigUint {
let zeros = ZERO_VEC.iter().cycle();
let (a, b) = if self.data.len() > other.data.len() { (self, other) } else { (other, self) };
let mut carry = 0;
let mut sum: Vec<BigDigit> = a.data.iter().zip(b.data.iter().chain(zeros)).map(|(ai, bi)| {
let (hi, lo) = BigDigit::from_doublebigdigit(
(*ai as DoubleBigDigit) + (*bi as DoubleBigDigit) + (carry as DoubleBigDigit));
carry = hi;
lo
}).collect();
if carry != 0 { sum.push(carry); }
return BigUint::new(sum);
}
}
impl Sub<BigUint, BigUint> for BigUint {
fn sub(&self, other: &BigUint) -> BigUint {
let new_len = cmp::max(self.data.len(), other.data.len());
let zeros = ZERO_VEC.iter().cycle();
let (a, b) = (self.data.iter().chain(zeros.clone()), other.data.iter().chain(zeros));
let mut borrow = 0i;
let diff: Vec<BigDigit> = a.take(new_len).zip(b).map(|(ai, bi)| {
let (hi, lo) = BigDigit::from_doublebigdigit(
BigDigit::base
+ (*ai as DoubleBigDigit)
- (*bi as DoubleBigDigit)
- (borrow as DoubleBigDigit)
);
/*
hi * (base) + lo == 1*(base) + ai - bi - borrow
=> ai - bi - borrow < 0 <=> hi == 0
*/
borrow = if hi == 0 { 1 } else { 0 };
lo
}).collect();
assert!(borrow == 0,
"Cannot subtract other from self because other is larger than self.");
return BigUint::new(diff);
}
}
impl Mul<BigUint, BigUint> for BigUint {
fn mul(&self, other: &BigUint) -> BigUint {
if self.is_zero() || other.is_zero() { return Zero::zero(); }
let (s_len, o_len) = (self.data.len(), other.data.len());
if s_len == 1 { return mul_digit(other, self.data.as_slice()[0]); }
if o_len == 1 { return mul_digit(self, other.data.as_slice()[0]); }
// Using Karatsuba multiplication
// (a1 * base + a0) * (b1 * base + b0)
// = a1*b1 * base^2 +
// (a1*b1 + a0*b0 - (a1-b0)*(b1-a0)) * base +
// a0*b0
let half_len = cmp::max(s_len, o_len) / 2;
let (s_hi, s_lo) = cut_at(self, half_len);
let (o_hi, o_lo) = cut_at(other, half_len);
let ll = s_lo * o_lo;
let hh = s_hi * o_hi;
let mm = {
let (s1, n1) = sub_sign(s_hi, s_lo);
let (s2, n2) = sub_sign(o_hi, o_lo);
match (s1, s2) {
(Equal, _) | (_, Equal) => hh + ll,
(Less, Greater) | (Greater, Less) => hh + ll + (n1 * n2),
(Less, Less) | (Greater, Greater) => hh + ll - (n1 * n2)
}
};
return ll + mm.shl_unit(half_len) + hh.shl_unit(half_len * 2);
fn mul_digit(a: &BigUint, n: BigDigit) -> BigUint {
if n == 0 { return Zero::zero(); }
if n == 1 { return (*a).clone(); }
let mut carry = 0;
let mut prod: Vec<BigDigit> = a.data.iter().map(|ai| {
let (hi, lo) = BigDigit::from_doublebigdigit(
(*ai as DoubleBigDigit) * (n as DoubleBigDigit) + (carry as DoubleBigDigit)
);
carry = hi;
lo
}).collect();
if carry != 0 { prod.push(carry); }
return BigUint::new(prod);
}
#[inline]
fn cut_at(a: &BigUint, n: uint) -> (BigUint, BigUint) {
let mid = cmp::min(a.data.len(), n);
return (BigUint::from_slice(a.data.slice(mid, a.data.len())),
BigUint::from_slice(a.data.slice(0, mid)));
}
#[inline]
fn sub_sign(a: BigUint, b: BigUint) -> (Ordering, BigUint) {
match a.cmp(&b) {
Less => (Less, b - a),
Greater => (Greater, a - b),
_ => (Equal, Zero::zero())
}
}
}
}
impl Div<BigUint, BigUint> for BigUint {
#[inline]
fn div(&self, other: &BigUint) -> BigUint {
let (q, _) = self.div_rem(other);
return q;
}
}
impl Rem<BigUint, BigUint> for BigUint {
#[inline]
fn rem(&self, other: &BigUint) -> BigUint {
let (_, r) = self.div_rem(other);
return r;
}
}
impl Neg<BigUint> for BigUint {
#[inline]
fn neg(&self) -> BigUint { fail!() }
}
impl CheckedAdd for BigUint {
#[inline]
fn checked_add(&self, v: &BigUint) -> Option<BigUint> {
return Some(self.add(v));
}
}
impl CheckedSub for BigUint {
#[inline]
fn checked_sub(&self, v: &BigUint) -> Option<BigUint> {
if *self < *v {
return None;
}
return Some(self.sub(v));
}
}
impl CheckedMul for BigUint {
#[inline]
fn checked_mul(&self, v: &BigUint) -> Option<BigUint> {
return Some(self.mul(v));
}
}
impl CheckedDiv for BigUint {
#[inline]
fn checked_div(&self, v: &BigUint) -> Option<BigUint> {
if v.is_zero() {
return None;
}
return Some(self.div(v));
}
}
impl Integer for BigUint {
#[inline]
fn div_rem(&self, other: &BigUint) -> (BigUint, BigUint) {
self.div_mod_floor(other)
}
#[inline]
fn div_floor(&self, other: &BigUint) -> BigUint {
let (d, _) = self.div_mod_floor(other);
return d;
}
#[inline]
fn mod_floor(&self, other: &BigUint) -> BigUint {
let (_, m) = self.div_mod_floor(other);
return m;
}
fn div_mod_floor(&self, other: &BigUint) -> (BigUint, BigUint) {
if other.is_zero() { fail!() }
if self.is_zero() { return (Zero::zero(), Zero::zero()); }
if *other == One::one() { return ((*self).clone(), Zero::zero()); }
match self.cmp(other) {
Less => return (Zero::zero(), (*self).clone()),
Equal => return (One::one(), Zero::zero()),
Greater => {} // Do nothing
}
let mut shift = 0;
let mut n = *other.data.last().unwrap();
while n < (1 << BigDigit::bits - 2) {
n <<= 1;
shift += 1;
}
assert!(shift < BigDigit::bits);
let (d, m) = div_mod_floor_inner(self << shift, other << shift);
return (d, m >> shift);
fn div_mod_floor_inner(a: BigUint, b: BigUint) -> (BigUint, BigUint) {
let mut m = a;
let mut d: BigUint = Zero::zero();
let mut n = 1;
while m >= b {
let (d0, d_unit, b_unit) = div_estimate(&m, &b, n);
let mut d0 = d0;
let mut prod = b * d0;
while prod > m {
// FIXME(#5992): assignment operator overloads
// d0 -= d_unit
d0 = d0 - d_unit;
// FIXME(#5992): assignment operator overloads
// prod -= b_unit;
prod = prod - b_unit
}
if d0.is_zero() {
n = 2;
continue;
}
n = 1;
// FIXME(#5992): assignment operator overloads
// d += d0;
d = d + d0;
// FIXME(#5992): assignment operator overloads
// m -= prod;
m = m - prod;
}
return (d, m);
}
fn div_estimate(a: &BigUint, b: &BigUint, n: uint)
-> (BigUint, BigUint, BigUint) {
if a.data.len() < n {
return (Zero::zero(), Zero::zero(), (*a).clone());
}
let an = a.data.tailn(a.data.len() - n);
let bn = *b.data.last().unwrap();
let mut d = Vec::with_capacity(an.len());
let mut carry = 0;
for elt in an.iter().rev() {
let ai = BigDigit::to_doublebigdigit(carry, *elt);
let di = ai / (bn as DoubleBigDigit);
assert!(di < BigDigit::base);
carry = (ai % (bn as DoubleBigDigit)) as BigDigit;
d.push(di as BigDigit)
}
d.reverse();
let shift = (a.data.len() - an.len()) - (b.data.len() - 1);
if shift == 0 {
return (BigUint::new(d), One::one(), (*b).clone());
}
let one: BigUint = One::one();
return (BigUint::new(d).shl_unit(shift),
one.shl_unit(shift),
b.shl_unit(shift));
}
}
/// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
///
/// The result is always positive.
#[inline]
fn gcd(&self, other: &BigUint) -> BigUint {
// Use Euclid's algorithm
let mut m = (*self).clone();
let mut n = (*other).clone();
while !m.is_zero() {
let temp = m;
m = n % temp;
n = temp;
}
return n;
}
/// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
#[inline]
fn lcm(&self, other: &BigUint) -> BigUint { ((*self * *other) / self.gcd(other)) }
/// Deprecated, use `is_multiple_of` instead.
#[deprecated = "function renamed to `is_multiple_of`"]
#[inline]
fn divides(&self, other: &BigUint) -> bool { return self.is_multiple_of(other); }
/// Returns `true` if the number is a multiple of `other`.
#[inline]
fn is_multiple_of(&self, other: &BigUint) -> bool { (*self % *other).is_zero() }
/// Returns `true` if the number is divisible by `2`.
#[inline]
fn is_even(&self) -> bool {
// Considering only the last digit.
match self.data.as_slice().head() {
Some(x) => x.is_even(),
None => true
}
}
/// Returns `true` if the number is not divisible by `2`.
#[inline]
fn is_odd(&self) -> bool { !self.is_even() }
}
impl ToPrimitive for BigUint {
#[inline]
fn to_i64(&self) -> Option<i64> {
self.to_u64().and_then(|n| {
// If top bit of u64 is set, it's too large to convert to i64.
if n >> 63 == 0 {
Some(n as i64)
} else {
None
}
})
}
// `DoubleBigDigit` size dependent
#[inline]
fn to_u64(&self) -> Option<u64> {
match self.data.len() {
0 => Some(0),
1 => Some(self.data.as_slice()[0] as u64),
2 => Some(BigDigit::to_doublebigdigit(self.data.as_slice()[1], self.data.as_slice()[0])
as u64),
_ => None
}
}
}
impl FromPrimitive for BigUint {
#[inline]
fn from_i64(n: i64) -> Option<BigUint> {
if n > 0 {
FromPrimitive::from_u64(n as u64)
} else if n == 0 {
Some(Zero::zero())
} else {
None
}
}
// `DoubleBigDigit` size dependent
#[inline]
fn from_u64(n: u64) -> Option<BigUint> {
let n = match BigDigit::from_doublebigdigit(n) {
(0, 0) => Zero::zero(),
(0, n0) => BigUint::new(vec!(n0)),
(n1, n0) => BigUint::new(vec!(n0, n1))
};
Some(n)
}
}
/// A generic trait for converting a value to a `BigUint`.
pub trait ToBigUint {
/// Converts the value of `self` to a `BigUint`.
fn to_biguint(&self) -> Option<BigUint>;
}
impl ToBigUint for BigInt {
#[inline]
fn to_biguint(&self) -> Option<BigUint> {
if self.sign == Plus {
Some(self.data.clone())
} else if self.sign == Zero {
Some(Zero::zero())
} else {
None
}
}
}
impl ToBigUint for BigUint {
#[inline]
fn to_biguint(&self) -> Option<BigUint> {
Some(self.clone())
}
}
macro_rules! impl_to_biguint(
($T:ty, $from_ty:path) => {
impl ToBigUint for $T {
#[inline]
fn to_biguint(&self) -> Option<BigUint> {
$from_ty(*self)
}
}
}
)
impl_to_biguint!(int, FromPrimitive::from_int)
impl_to_biguint!(i8, FromPrimitive::from_i8)
impl_to_biguint!(i16, FromPrimitive::from_i16)
impl_to_biguint!(i32, FromPrimitive::from_i32)
impl_to_biguint!(i64, FromPrimitive::from_i64)
impl_to_biguint!(uint, FromPrimitive::from_uint)
impl_to_biguint!(u8, FromPrimitive::from_u8)
impl_to_biguint!(u16, FromPrimitive::from_u16)
impl_to_biguint!(u32, FromPrimitive::from_u32)
impl_to_biguint!(u64, FromPrimitive::from_u64)
impl ToStrRadix for BigUint {
fn to_str_radix(&self, radix: uint) -> String {
assert!(1 < radix && radix <= 16, "The radix must be within (1, 16]");
let (base, max_len) = get_radix_base(radix);
if base == BigDigit::base {
return fill_concat(self.data.as_slice(), radix, max_len)
}
return fill_concat(convert_base(self, base).as_slice(), radix, max_len);
fn convert_base(n: &BigUint, base: DoubleBigDigit) -> Vec<BigDigit> {
let divider = base.to_biguint().unwrap();
let mut result = Vec::new();
let mut m = n.clone();
while m >= divider {
let (d, m0) = m.div_mod_floor(÷r);
result.push(m0.to_uint().unwrap() as BigDigit);
m = d;
}
if !m.is_zero() {
result.push(m.to_uint().unwrap() as BigDigit);
}
return result;
}
fn fill_concat(v: &[BigDigit], radix: uint, l: uint) -> String {
if v.is_empty() {
return "0".to_string()
}
let mut s = String::with_capacity(v.len() * l);
for n in v.iter().rev() {
let ss = (*n as uint).to_str_radix(radix);
s.push_str("0".repeat(l - ss.len()).as_slice());
s.push_str(ss.as_slice());
}
s.as_slice().trim_left_chars('0').to_string()
}
}
}
impl FromStrRadix for BigUint {
/// Creates and initializes a `BigUint`.
#[inline]
fn from_str_radix(s: &str, radix: uint) -> Option<BigUint> {
BigUint::parse_bytes(s.as_bytes(), radix)
}
}
impl BigUint {
/// Creates and initializes a `BigUint`.
///
/// The digits are be in base 2^32.
#[inline]
pub fn new(mut digits: Vec<BigDigit>) -> BigUint {
// omit trailing zeros
let new_len = digits.iter().rposition(|n| *n != 0).map_or(0, |p| p + 1);
digits.truncate(new_len);
BigUint { data: digits }
}
/// Creates and initializes a `BigUint`.
///
/// The digits are be in base 2^32.
#[inline]
pub fn from_slice(slice: &[BigDigit]) -> BigUint {
BigUint::new(Vec::from_slice(slice))
}
/// Creates and initializes a `BigUint`.
pub fn parse_bytes(buf: &[u8], radix: uint) -> Option<BigUint> {
let (base, unit_len) = get_radix_base(radix);
let base_num = match base.to_biguint() {
Some(base_num) => base_num,
None => { return None; }
};
let mut end = buf.len();
let mut n: BigUint = Zero::zero();
let mut power: BigUint = One::one();
loop {
let start = cmp::max(end, unit_len) - unit_len;
match uint::parse_bytes(buf.slice(start, end), radix) {
Some(d) => {
let d: Option<BigUint> = FromPrimitive::from_uint(d);
match d {
Some(d) => {
// FIXME(#5992): assignment operator overloads
// n += d * power;
n = n + d * power;
}
None => { return None; }
}
}
None => { return None; }
}
if end <= unit_len {
return Some(n);
}
end -= unit_len;
// FIXME(#5992): assignment operator overloads
// power *= base_num;
power = power * base_num;
}
}
#[inline]
fn shl_unit(&self, n_unit: uint) -> BigUint {
if n_unit == 0 || self.is_zero() { return (*self).clone(); }
BigUint::new(Vec::from_elem(n_unit, ZERO_BIG_DIGIT).append(self.data.as_slice()))
}
#[inline]
fn shl_bits(&self, n_bits: uint) -> BigUint {
if n_bits == 0 || self.is_zero() { return (*self).clone(); }
let mut carry = 0;
let mut shifted: Vec<BigDigit> = self.data.iter().map(|elem| {
let (hi, lo) = BigDigit::from_doublebigdigit(
(*elem as DoubleBigDigit) << n_bits | (carry as DoubleBigDigit)
);
carry = hi;
lo
}).collect();
if carry != 0 { shifted.push(carry); }
return BigUint::new(shifted);
}
#[inline]
fn shr_unit(&self, n_unit: uint) -> BigUint {
if n_unit == 0 { return (*self).clone(); }
if self.data.len() < n_unit { return Zero::zero(); }
return BigUint::from_slice(
self.data.slice(n_unit, self.data.len())
);
}
#[inline]
fn shr_bits(&self, n_bits: uint) -> BigUint {
if n_bits == 0 || self.data.is_empty() { return (*self).clone(); }
let mut borrow = 0;
let mut shifted_rev = Vec::with_capacity(self.data.len());
for elem in self.data.iter().rev() {
shifted_rev.push((*elem >> n_bits) | borrow);
borrow = *elem << (BigDigit::bits - n_bits);
}
let shifted = { shifted_rev.reverse(); shifted_rev };
return BigUint::new(shifted);
}
/// Determines the fewest bits necessary to express the `BigUint`.
pub fn bits(&self) -> uint {
if self.is_zero() { return 0; }
let zeros = self.data.last().unwrap().leading_zeros();
return self.data.len()*BigDigit::bits - (zeros as uint);
}
}
// `DoubleBigDigit` size dependent
#[inline]
fn get_radix_base(radix: uint) -> (DoubleBigDigit, uint) {
match radix {
2 => (4294967296, 32),
3 => (3486784401, 20),
4 => (4294967296, 16),
5 => (1220703125, 13),
6 => (2176782336, 12),
7 => (1977326743, 11),
8 => (1073741824, 10),
9 => (3486784401, 10),
10 => (1000000000, 9),
11 => (2357947691, 9),
12 => (429981696, 8),
13 => (815730721, 8),
14 => (1475789056, 8),
15 => (2562890625, 8),
16 => (4294967296, 8),
_ => fail!("The radix must be within (1, 16]")
}
}
/// A Sign is a `BigInt`'s composing element.
#[deriving(PartialEq, PartialOrd, Eq, Ord, Clone, Show)]
pub enum Sign { Minus, Zero, Plus }
impl Neg<Sign> for Sign {
/// Negate Sign value.
#[inline]
fn neg(&self) -> Sign {
match *self {
Minus => Plus,
Zero => Zero,
Plus => Minus
}
}
}
/// A big signed integer type.
#[deriving(Clone)]
pub struct BigInt {
sign: Sign,
data: BigUint
}
impl PartialEq for BigInt {
#[inline]
fn eq(&self, other: &BigInt) -> bool {
self.cmp(other) == Equal
}
}
impl Eq for BigInt {}
impl PartialOrd for BigInt {
#[inline]
fn partial_cmp(&self, other: &BigInt) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for BigInt {
#[inline]
fn cmp(&self, other: &BigInt) -> Ordering {
let scmp = self.sign.cmp(&other.sign);
if scmp != Equal { return scmp; }
match self.sign {
Zero => Equal,
Plus => self.data.cmp(&other.data),
Minus => other.data.cmp(&self.data),
}
}
}
impl Default for BigInt {
#[inline]
fn default() -> BigInt { Zero::zero() }
}
impl fmt::Show for BigInt {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.to_str_radix(10))
}
}
impl FromStr for BigInt {
#[inline]
fn from_str(s: &str) -> Option<BigInt> {
FromStrRadix::from_str_radix(s, 10)
}
}
impl Num for BigInt {}
impl Shl<uint, BigInt> for BigInt {
#[inline]
fn shl(&self, rhs: &uint) -> BigInt {
BigInt::from_biguint(self.sign, self.data << *rhs)
}
}
impl Shr<uint, BigInt> for BigInt {
#[inline]
fn shr(&self, rhs: &uint) -> BigInt {
BigInt::from_biguint(self.sign, self.data >> *rhs)
}
}
impl Zero for BigInt {
#[inline]
fn zero() -> BigInt {
BigInt::from_biguint(Zero, Zero::zero())
}
#[inline]
fn is_zero(&self) -> bool { self.sign == Zero }
}
impl One for BigInt {
#[inline]
fn one() -> BigInt {
BigInt::from_biguint(Plus, One::one())
}
}
impl Signed for BigInt {
#[inline]
fn abs(&self) -> BigInt {
match self.sign {
Plus | Zero => self.clone(),
Minus => BigInt::from_biguint(Plus, self.data.clone())
}
}
#[inline]
fn abs_sub(&self, other: &BigInt) -> BigInt {
if *self <= *other { Zero::zero() } else { *self - *other }
}
#[inline]
fn signum(&self) -> BigInt {
match self.sign {
Plus => BigInt::from_biguint(Plus, One::one()),
Minus => BigInt::from_biguint(Minus, One::one()),
Zero => Zero::zero(),
}
}
#[inline]
fn is_positive(&self) -> bool { self.sign == Plus }
#[inline]
fn is_negative(&self) -> bool { self.sign == Minus }
}
impl Add<BigInt, BigInt> for BigInt {
#[inline]
fn add(&self, other: &BigInt) -> BigInt {
match (self.sign, other.sign) {
(Zero, _) => other.clone(),
(_, Zero) => self.clone(),
(Plus, Plus) => BigInt::from_biguint(Plus, self.data + other.data),
(Plus, Minus) => self - (-*other),
(Minus, Plus) => other - (-*self),
(Minus, Minus) => -((-self) + (-*other))
}
}
}
impl Sub<BigInt, BigInt> for BigInt {
#[inline]
fn sub(&self, other: &BigInt) -> BigInt {
match (self.sign, other.sign) {
(Zero, _) => -other,
(_, Zero) => self.clone(),
(Plus, Plus) => match self.data.cmp(&other.data) {
Less => BigInt::from_biguint(Minus, other.data - self.data),
Greater => BigInt::from_biguint(Plus, self.data - other.data),
Equal => Zero::zero()
},
(Plus, Minus) => self + (-*other),
(Minus, Plus) => -((-self) + *other),
(Minus, Minus) => (-other) - (-*self)
}
}
}
impl Mul<BigInt, BigInt> for BigInt {
#[inline]
fn mul(&self, other: &BigInt) -> BigInt {
match (self.sign, other.sign) {
(Zero, _) | (_, Zero) => Zero::zero(),
(Plus, Plus) | (Minus, Minus) => {
BigInt::from_biguint(Plus, self.data * other.data)
},
(Plus, Minus) | (Minus, Plus) => {
BigInt::from_biguint(Minus, self.data * other.data)
}
}
}
}