1#![doc(html_root_url = "https://docs.rs/num-integer/0.1")]
18#![no_std]
19
20use core::mem;
21use core::ops::Add;
22
23use num_traits::{Num, Signed, Zero};
24
25mod roots;
26pub use crate::roots::Roots;
27pub use crate::roots::{cbrt, nth_root, sqrt};
28
29mod average;
30pub use crate::average::Average;
31pub use crate::average::{average_ceil, average_floor};
32
33pub trait Integer: Sized + Num + PartialOrd + Ord + Eq {
34 fn div_floor(&self, other: &Self) -> Self;
51
52 fn mod_floor(&self, other: &Self) -> Self;
75
76 fn div_ceil(&self, other: &Self) -> Self {
93 let (q, r) = self.div_mod_floor(other);
94 if r.is_zero() {
95 q
96 } else {
97 q + Self::one()
98 }
99 }
100
101 fn gcd(&self, other: &Self) -> Self;
113
114 fn lcm(&self, other: &Self) -> Self;
125
126 #[inline]
140 fn gcd_lcm(&self, other: &Self) -> (Self, Self) {
141 (self.gcd(other), self.lcm(other))
142 }
143
144 #[inline]
161 fn extended_gcd(&self, other: &Self) -> ExtendedGcd<Self>
162 where
163 Self: Clone,
164 {
165 let mut s = (Self::zero(), Self::one());
166 let mut t = (Self::one(), Self::zero());
167 let mut r = (other.clone(), self.clone());
168
169 while !r.0.is_zero() {
170 let q = r.1.clone() / r.0.clone();
171 let f = |mut r: (Self, Self)| {
172 mem::swap(&mut r.0, &mut r.1);
173 r.0 = r.0 - q.clone() * r.1.clone();
174 r
175 };
176 r = f(r);
177 s = f(s);
178 t = f(t);
179 }
180
181 if r.1 >= Self::zero() {
182 ExtendedGcd {
183 gcd: r.1,
184 x: s.1,
185 y: t.1,
186 }
187 } else {
188 ExtendedGcd {
189 gcd: Self::zero() - r.1,
190 x: Self::zero() - s.1,
191 y: Self::zero() - t.1,
192 }
193 }
194 }
195
196 #[inline]
198 fn extended_gcd_lcm(&self, other: &Self) -> (ExtendedGcd<Self>, Self)
199 where
200 Self: Clone + Signed,
201 {
202 (self.extended_gcd(other), self.lcm(other))
203 }
204
205 #[deprecated(note = "Please use is_multiple_of instead")]
207 #[inline]
208 fn divides(&self, other: &Self) -> bool {
209 self.is_multiple_of(other)
210 }
211
212 fn is_multiple_of(&self, other: &Self) -> bool;
222
223 fn is_even(&self) -> bool;
233
234 fn is_odd(&self) -> bool;
244
245 fn div_rem(&self, other: &Self) -> (Self, Self);
263
264 fn div_mod_floor(&self, other: &Self) -> (Self, Self) {
282 (self.div_floor(other), self.mod_floor(other))
283 }
284
285 #[inline]
305 fn next_multiple_of(&self, other: &Self) -> Self
306 where
307 Self: Clone,
308 {
309 let m = self.mod_floor(other);
310 self.clone()
311 + if m.is_zero() {
312 Self::zero()
313 } else {
314 other.clone() - m
315 }
316 }
317
318 #[inline]
338 fn prev_multiple_of(&self, other: &Self) -> Self
339 where
340 Self: Clone,
341 {
342 self.clone() - self.mod_floor(other)
343 }
344
345 fn dec(&mut self)
356 where
357 Self: Clone,
358 {
359 *self = self.clone() - Self::one()
360 }
361
362 fn inc(&mut self)
373 where
374 Self: Clone,
375 {
376 *self = self.clone() + Self::one()
377 }
378}
379
380#[derive(Debug, Clone, Copy, PartialEq, Eq)]
387pub struct ExtendedGcd<A> {
388 pub gcd: A,
389 pub x: A,
390 pub y: A,
391}
392
393#[inline]
395pub fn div_rem<T: Integer>(x: T, y: T) -> (T, T) {
396 x.div_rem(&y)
397}
398#[inline]
400pub fn div_floor<T: Integer>(x: T, y: T) -> T {
401 x.div_floor(&y)
402}
403#[inline]
405pub fn mod_floor<T: Integer>(x: T, y: T) -> T {
406 x.mod_floor(&y)
407}
408#[inline]
410pub fn div_mod_floor<T: Integer>(x: T, y: T) -> (T, T) {
411 x.div_mod_floor(&y)
412}
413#[inline]
415pub fn div_ceil<T: Integer>(x: T, y: T) -> T {
416 x.div_ceil(&y)
417}
418
419#[inline(always)]
422pub fn gcd<T: Integer>(x: T, y: T) -> T {
423 x.gcd(&y)
424}
425#[inline(always)]
427pub fn lcm<T: Integer>(x: T, y: T) -> T {
428 x.lcm(&y)
429}
430
431#[inline(always)]
434pub fn gcd_lcm<T: Integer>(x: T, y: T) -> (T, T) {
435 x.gcd_lcm(&y)
436}
437
438macro_rules! impl_integer_for_isize {
439 ($T:ty, $test_mod:ident) => {
440 impl Integer for $T {
441 #[inline]
443 fn div_floor(&self, other: &Self) -> Self {
444 let (d, r) = self.div_rem(other);
447 if (r > 0 && *other < 0) || (r < 0 && *other > 0) {
448 d - 1
449 } else {
450 d
451 }
452 }
453
454 #[inline]
456 fn mod_floor(&self, other: &Self) -> Self {
457 let r = *self % *other;
460 if (r > 0 && *other < 0) || (r < 0 && *other > 0) {
461 r + *other
462 } else {
463 r
464 }
465 }
466
467 #[inline]
469 fn div_mod_floor(&self, other: &Self) -> (Self, Self) {
470 let (d, r) = self.div_rem(other);
473 if (r > 0 && *other < 0) || (r < 0 && *other > 0) {
474 (d - 1, r + *other)
475 } else {
476 (d, r)
477 }
478 }
479
480 #[inline]
481 fn div_ceil(&self, other: &Self) -> Self {
482 let (d, r) = self.div_rem(other);
483 if (r > 0 && *other > 0) || (r < 0 && *other < 0) {
484 d + 1
485 } else {
486 d
487 }
488 }
489
490 #[inline]
493 fn gcd(&self, other: &Self) -> Self {
494 let mut m = *self;
496 let mut n = *other;
497 if m == 0 || n == 0 {
498 return (m | n).abs();
499 }
500
501 let shift = (m | n).trailing_zeros();
503
504 if m == Self::min_value() || n == Self::min_value() {
513 return (1 << shift).abs();
514 }
515
516 m = m.abs();
518 n = n.abs();
519
520 m >>= m.trailing_zeros();
522 n >>= n.trailing_zeros();
523
524 while m != n {
525 if m > n {
526 m -= n;
527 m >>= m.trailing_zeros();
528 } else {
529 n -= m;
530 n >>= n.trailing_zeros();
531 }
532 }
533 m << shift
534 }
535
536 #[inline]
537 fn extended_gcd_lcm(&self, other: &Self) -> (ExtendedGcd<Self>, Self) {
538 let egcd = self.extended_gcd(other);
539 let lcm = if egcd.gcd.is_zero() {
541 Self::zero()
542 } else {
543 (*self * (*other / egcd.gcd)).abs()
544 };
545 (egcd, lcm)
546 }
547
548 #[inline]
551 fn lcm(&self, other: &Self) -> Self {
552 self.gcd_lcm(other).1
553 }
554
555 #[inline]
558 fn gcd_lcm(&self, other: &Self) -> (Self, Self) {
559 if self.is_zero() && other.is_zero() {
560 return (Self::zero(), Self::zero());
561 }
562 let gcd = self.gcd(other);
563 let lcm = (*self * (*other / gcd)).abs();
565 (gcd, lcm)
566 }
567
568 #[inline]
570 fn is_multiple_of(&self, other: &Self) -> bool {
571 if other.is_zero() {
572 return self.is_zero();
573 }
574 *self % *other == 0
575 }
576
577 #[inline]
579 fn is_even(&self) -> bool {
580 (*self) & 1 == 0
581 }
582
583 #[inline]
585 fn is_odd(&self) -> bool {
586 !self.is_even()
587 }
588
589 #[inline]
591 fn div_rem(&self, other: &Self) -> (Self, Self) {
592 (*self / *other, *self % *other)
593 }
594
595 #[inline]
597 fn next_multiple_of(&self, other: &Self) -> Self {
598 if *other == -1 {
600 return *self;
601 }
602
603 let m = Integer::mod_floor(self, other);
604 *self + if m == 0 { 0 } else { other - m }
605 }
606
607 #[inline]
609 fn prev_multiple_of(&self, other: &Self) -> Self {
610 if *other == -1 {
612 return *self;
613 }
614
615 *self - Integer::mod_floor(self, other)
616 }
617 }
618
619 #[cfg(test)]
620 mod $test_mod {
621 use crate::Integer;
622 use core::mem;
623
624 #[cfg(test)]
630 fn test_division_rule((n, d): ($T, $T), (q, r): ($T, $T)) {
631 assert_eq!(d * q + r, n);
632 }
633
634 #[test]
635 fn test_div_rem() {
636 fn test_nd_dr(nd: ($T, $T), qr: ($T, $T)) {
637 let (n, d) = nd;
638 let separate_div_rem = (n / d, n % d);
639 let combined_div_rem = n.div_rem(&d);
640
641 test_division_rule(nd, qr);
642
643 assert_eq!(separate_div_rem, qr);
644 assert_eq!(combined_div_rem, qr);
645 }
646
647 test_nd_dr((8, 3), (2, 2));
648 test_nd_dr((8, -3), (-2, 2));
649 test_nd_dr((-8, 3), (-2, -2));
650 test_nd_dr((-8, -3), (2, -2));
651
652 test_nd_dr((1, 2), (0, 1));
653 test_nd_dr((1, -2), (0, 1));
654 test_nd_dr((-1, 2), (0, -1));
655 test_nd_dr((-1, -2), (0, -1));
656 }
657
658 #[test]
659 fn test_div_mod_floor() {
660 fn test_nd_dm(nd: ($T, $T), dm: ($T, $T)) {
661 let (n, d) = nd;
662 let separate_div_mod_floor =
663 (Integer::div_floor(&n, &d), Integer::mod_floor(&n, &d));
664 let combined_div_mod_floor = Integer::div_mod_floor(&n, &d);
665
666 test_division_rule(nd, dm);
667
668 assert_eq!(separate_div_mod_floor, dm);
669 assert_eq!(combined_div_mod_floor, dm);
670 }
671
672 test_nd_dm((8, 3), (2, 2));
673 test_nd_dm((8, -3), (-3, -1));
674 test_nd_dm((-8, 3), (-3, 1));
675 test_nd_dm((-8, -3), (2, -2));
676
677 test_nd_dm((1, 2), (0, 1));
678 test_nd_dm((1, -2), (-1, -1));
679 test_nd_dm((-1, 2), (-1, 1));
680 test_nd_dm((-1, -2), (0, -1));
681 }
682
683 #[test]
684 fn test_gcd() {
685 assert_eq!((10 as $T).gcd(&2), 2 as $T);
686 assert_eq!((10 as $T).gcd(&3), 1 as $T);
687 assert_eq!((0 as $T).gcd(&3), 3 as $T);
688 assert_eq!((3 as $T).gcd(&3), 3 as $T);
689 assert_eq!((56 as $T).gcd(&42), 14 as $T);
690 assert_eq!((3 as $T).gcd(&-3), 3 as $T);
691 assert_eq!((-6 as $T).gcd(&3), 3 as $T);
692 assert_eq!((-4 as $T).gcd(&-2), 2 as $T);
693 }
694
695 #[test]
696 fn test_gcd_cmp_with_euclidean() {
697 fn euclidean_gcd(mut m: $T, mut n: $T) -> $T {
698 while m != 0 {
699 mem::swap(&mut m, &mut n);
700 m %= n;
701 }
702
703 n.abs()
704 }
705
706 for i in -127..=127 {
709 for j in -127..=127 {
710 assert_eq!(euclidean_gcd(i, j), i.gcd(&j));
711 }
712 }
713 }
714
715 #[test]
716 fn test_gcd_min_val() {
717 let min = <$T>::min_value();
718 let max = <$T>::max_value();
719 let max_pow2 = max / 2 + 1;
720 assert_eq!(min.gcd(&max), 1 as $T);
721 assert_eq!(max.gcd(&min), 1 as $T);
722 assert_eq!(min.gcd(&max_pow2), max_pow2);
723 assert_eq!(max_pow2.gcd(&min), max_pow2);
724 assert_eq!(min.gcd(&42), 2 as $T);
725 assert_eq!((42 as $T).gcd(&min), 2 as $T);
726 }
727
728 #[test]
729 #[should_panic]
730 fn test_gcd_min_val_min_val() {
731 let min = <$T>::min_value();
732 assert!(min.gcd(&min) >= 0);
733 }
734
735 #[test]
736 #[should_panic]
737 fn test_gcd_min_val_0() {
738 let min = <$T>::min_value();
739 assert!(min.gcd(&0) >= 0);
740 }
741
742 #[test]
743 #[should_panic]
744 fn test_gcd_0_min_val() {
745 let min = <$T>::min_value();
746 assert!((0 as $T).gcd(&min) >= 0);
747 }
748
749 #[test]
750 fn test_lcm() {
751 assert_eq!((1 as $T).lcm(&0), 0 as $T);
752 assert_eq!((0 as $T).lcm(&1), 0 as $T);
753 assert_eq!((1 as $T).lcm(&1), 1 as $T);
754 assert_eq!((-1 as $T).lcm(&1), 1 as $T);
755 assert_eq!((1 as $T).lcm(&-1), 1 as $T);
756 assert_eq!((-1 as $T).lcm(&-1), 1 as $T);
757 assert_eq!((8 as $T).lcm(&9), 72 as $T);
758 assert_eq!((11 as $T).lcm(&5), 55 as $T);
759 }
760
761 #[test]
762 fn test_gcd_lcm() {
763 use core::iter::once;
764 for i in once(0)
765 .chain((1..).take(127).flat_map(|a| once(a).chain(once(-a))))
766 .chain(once(-128))
767 {
768 for j in once(0)
769 .chain((1..).take(127).flat_map(|a| once(a).chain(once(-a))))
770 .chain(once(-128))
771 {
772 assert_eq!(i.gcd_lcm(&j), (i.gcd(&j), i.lcm(&j)));
773 }
774 }
775 }
776
777 #[test]
778 fn test_extended_gcd_lcm() {
779 use crate::ExtendedGcd;
780 use core::fmt::Debug;
781 use num_traits::NumAssign;
782
783 fn check<A: Copy + Debug + Integer + NumAssign>(a: A, b: A) {
784 let ExtendedGcd { gcd, x, y, .. } = a.extended_gcd(&b);
785 assert_eq!(gcd, x * a + y * b);
786 }
787
788 use core::iter::once;
789 for i in once(0)
790 .chain((1..).take(127).flat_map(|a| once(a).chain(once(-a))))
791 .chain(once(-128))
792 {
793 for j in once(0)
794 .chain((1..).take(127).flat_map(|a| once(a).chain(once(-a))))
795 .chain(once(-128))
796 {
797 check(i, j);
798 let (ExtendedGcd { gcd, .. }, lcm) = i.extended_gcd_lcm(&j);
799 assert_eq!((gcd, lcm), (i.gcd(&j), i.lcm(&j)));
800 }
801 }
802 }
803
804 #[test]
805 fn test_even() {
806 assert_eq!((-4 as $T).is_even(), true);
807 assert_eq!((-3 as $T).is_even(), false);
808 assert_eq!((-2 as $T).is_even(), true);
809 assert_eq!((-1 as $T).is_even(), false);
810 assert_eq!((0 as $T).is_even(), true);
811 assert_eq!((1 as $T).is_even(), false);
812 assert_eq!((2 as $T).is_even(), true);
813 assert_eq!((3 as $T).is_even(), false);
814 assert_eq!((4 as $T).is_even(), true);
815 }
816
817 #[test]
818 fn test_odd() {
819 assert_eq!((-4 as $T).is_odd(), false);
820 assert_eq!((-3 as $T).is_odd(), true);
821 assert_eq!((-2 as $T).is_odd(), false);
822 assert_eq!((-1 as $T).is_odd(), true);
823 assert_eq!((0 as $T).is_odd(), false);
824 assert_eq!((1 as $T).is_odd(), true);
825 assert_eq!((2 as $T).is_odd(), false);
826 assert_eq!((3 as $T).is_odd(), true);
827 assert_eq!((4 as $T).is_odd(), false);
828 }
829
830 #[test]
831 fn test_multiple_of_one_limits() {
832 for x in &[<$T>::min_value(), <$T>::max_value()] {
833 for one in &[1, -1] {
834 assert_eq!(Integer::next_multiple_of(x, one), *x);
835 assert_eq!(Integer::prev_multiple_of(x, one), *x);
836 }
837 }
838 }
839 }
840 };
841}
842
843impl_integer_for_isize!(i8, test_integer_i8);
844impl_integer_for_isize!(i16, test_integer_i16);
845impl_integer_for_isize!(i32, test_integer_i32);
846impl_integer_for_isize!(i64, test_integer_i64);
847impl_integer_for_isize!(i128, test_integer_i128);
848impl_integer_for_isize!(isize, test_integer_isize);
849
850macro_rules! impl_integer_for_usize {
851 ($T:ty, $test_mod:ident) => {
852 impl Integer for $T {
853 #[inline]
855 fn div_floor(&self, other: &Self) -> Self {
856 *self / *other
857 }
858
859 #[inline]
861 fn mod_floor(&self, other: &Self) -> Self {
862 *self % *other
863 }
864
865 #[inline]
866 fn div_ceil(&self, other: &Self) -> Self {
867 *self / *other + (0 != *self % *other) as Self
868 }
869
870 #[inline]
872 fn gcd(&self, other: &Self) -> Self {
873 let mut m = *self;
875 let mut n = *other;
876 if m == 0 || n == 0 {
877 return m | n;
878 }
879
880 let shift = (m | n).trailing_zeros();
882
883 m >>= m.trailing_zeros();
885 n >>= n.trailing_zeros();
886
887 while m != n {
888 if m > n {
889 m -= n;
890 m >>= m.trailing_zeros();
891 } else {
892 n -= m;
893 n >>= n.trailing_zeros();
894 }
895 }
896 m << shift
897 }
898
899 #[inline]
900 fn extended_gcd_lcm(&self, other: &Self) -> (ExtendedGcd<Self>, Self) {
901 let egcd = self.extended_gcd(other);
902 let lcm = if egcd.gcd.is_zero() {
904 Self::zero()
905 } else {
906 *self * (*other / egcd.gcd)
907 };
908 (egcd, lcm)
909 }
910
911 #[inline]
913 fn lcm(&self, other: &Self) -> Self {
914 self.gcd_lcm(other).1
915 }
916
917 #[inline]
920 fn gcd_lcm(&self, other: &Self) -> (Self, Self) {
921 if self.is_zero() && other.is_zero() {
922 return (Self::zero(), Self::zero());
923 }
924 let gcd = self.gcd(other);
925 let lcm = *self * (*other / gcd);
926 (gcd, lcm)
927 }
928
929 #[inline]
931 fn is_multiple_of(&self, other: &Self) -> bool {
932 if other.is_zero() {
933 return self.is_zero();
934 }
935 *self % *other == 0
936 }
937
938 #[inline]
940 fn is_even(&self) -> bool {
941 *self % 2 == 0
942 }
943
944 #[inline]
946 fn is_odd(&self) -> bool {
947 !self.is_even()
948 }
949
950 #[inline]
952 fn div_rem(&self, other: &Self) -> (Self, Self) {
953 (*self / *other, *self % *other)
954 }
955 }
956
957 #[cfg(test)]
958 mod $test_mod {
959 use crate::Integer;
960 use core::mem;
961
962 #[test]
963 fn test_div_mod_floor() {
964 assert_eq!(<$T as Integer>::div_floor(&10, &3), 3 as $T);
965 assert_eq!(<$T as Integer>::mod_floor(&10, &3), 1 as $T);
966 assert_eq!(<$T as Integer>::div_mod_floor(&10, &3), (3 as $T, 1 as $T));
967 assert_eq!(<$T as Integer>::div_floor(&5, &5), 1 as $T);
968 assert_eq!(<$T as Integer>::mod_floor(&5, &5), 0 as $T);
969 assert_eq!(<$T as Integer>::div_mod_floor(&5, &5), (1 as $T, 0 as $T));
970 assert_eq!(<$T as Integer>::div_floor(&3, &7), 0 as $T);
971 assert_eq!(<$T as Integer>::div_floor(&3, &7), 0 as $T);
972 assert_eq!(<$T as Integer>::mod_floor(&3, &7), 3 as $T);
973 assert_eq!(<$T as Integer>::div_mod_floor(&3, &7), (0 as $T, 3 as $T));
974 }
975
976 #[test]
977 fn test_gcd() {
978 assert_eq!((10 as $T).gcd(&2), 2 as $T);
979 assert_eq!((10 as $T).gcd(&3), 1 as $T);
980 assert_eq!((0 as $T).gcd(&3), 3 as $T);
981 assert_eq!((3 as $T).gcd(&3), 3 as $T);
982 assert_eq!((56 as $T).gcd(&42), 14 as $T);
983 }
984
985 #[test]
986 fn test_gcd_cmp_with_euclidean() {
987 fn euclidean_gcd(mut m: $T, mut n: $T) -> $T {
988 while m != 0 {
989 mem::swap(&mut m, &mut n);
990 m %= n;
991 }
992 n
993 }
994
995 for i in 0..=255 {
996 for j in 0..=255 {
997 assert_eq!(euclidean_gcd(i, j), i.gcd(&j));
998 }
999 }
1000 }
1001
1002 #[test]
1003 fn test_lcm() {
1004 assert_eq!((1 as $T).lcm(&0), 0 as $T);
1005 assert_eq!((0 as $T).lcm(&1), 0 as $T);
1006 assert_eq!((1 as $T).lcm(&1), 1 as $T);
1007 assert_eq!((8 as $T).lcm(&9), 72 as $T);
1008 assert_eq!((11 as $T).lcm(&5), 55 as $T);
1009 assert_eq!((15 as $T).lcm(&17), 255 as $T);
1010 }
1011
1012 #[test]
1013 fn test_gcd_lcm() {
1014 for i in (0..).take(256) {
1015 for j in (0..).take(256) {
1016 assert_eq!(i.gcd_lcm(&j), (i.gcd(&j), i.lcm(&j)));
1017 }
1018 }
1019 }
1020
1021 #[test]
1022 fn test_is_multiple_of() {
1023 assert!(<$T as Integer>::is_multiple_of(&(0 as $T), &(0 as $T)));
1024 assert!(<$T as Integer>::is_multiple_of(&(6 as $T), &(6 as $T)));
1025 assert!(<$T as Integer>::is_multiple_of(&(6 as $T), &(3 as $T)));
1026 assert!(<$T as Integer>::is_multiple_of(&(6 as $T), &(1 as $T)));
1027
1028 assert!(!<$T as Integer>::is_multiple_of(&(42 as $T), &(5 as $T)));
1029 assert!(!<$T as Integer>::is_multiple_of(&(5 as $T), &(3 as $T)));
1030 assert!(!<$T as Integer>::is_multiple_of(&(42 as $T), &(0 as $T)));
1031 }
1032
1033 #[test]
1034 fn test_even() {
1035 assert_eq!((0 as $T).is_even(), true);
1036 assert_eq!((1 as $T).is_even(), false);
1037 assert_eq!((2 as $T).is_even(), true);
1038 assert_eq!((3 as $T).is_even(), false);
1039 assert_eq!((4 as $T).is_even(), true);
1040 }
1041
1042 #[test]
1043 fn test_odd() {
1044 assert_eq!((0 as $T).is_odd(), false);
1045 assert_eq!((1 as $T).is_odd(), true);
1046 assert_eq!((2 as $T).is_odd(), false);
1047 assert_eq!((3 as $T).is_odd(), true);
1048 assert_eq!((4 as $T).is_odd(), false);
1049 }
1050 }
1051 };
1052}
1053
1054impl_integer_for_usize!(u8, test_integer_u8);
1055impl_integer_for_usize!(u16, test_integer_u16);
1056impl_integer_for_usize!(u32, test_integer_u32);
1057impl_integer_for_usize!(u64, test_integer_u64);
1058impl_integer_for_usize!(u128, test_integer_u128);
1059impl_integer_for_usize!(usize, test_integer_usize);
1060
1061pub struct IterBinomial<T> {
1063 a: T,
1064 n: T,
1065 k: T,
1066}
1067
1068impl<T> IterBinomial<T>
1069where
1070 T: Integer,
1071{
1072 pub fn new(n: T) -> IterBinomial<T> {
1091 IterBinomial {
1092 k: T::zero(),
1093 a: T::one(),
1094 n,
1095 }
1096 }
1097}
1098
1099impl<T> Iterator for IterBinomial<T>
1100where
1101 T: Integer + Clone,
1102{
1103 type Item = T;
1104
1105 fn next(&mut self) -> Option<T> {
1106 if self.k > self.n {
1107 return None;
1108 }
1109 self.a = if !self.k.is_zero() {
1110 multiply_and_divide(
1111 self.a.clone(),
1112 self.n.clone() - self.k.clone() + T::one(),
1113 self.k.clone(),
1114 )
1115 } else {
1116 T::one()
1117 };
1118 self.k = self.k.clone() + T::one();
1119 Some(self.a.clone())
1120 }
1121}
1122
1123fn multiply_and_divide<T: Integer + Clone>(r: T, a: T, b: T) -> T {
1127 let g = gcd(r.clone(), b.clone());
1129 r / g.clone() * (a / (b / g))
1130}
1131
1132pub fn binomial<T: Integer + Clone>(mut n: T, k: T) -> T {
1151 if k > n {
1153 return T::zero();
1154 }
1155 if k > n.clone() - k.clone() {
1156 return binomial(n.clone(), n - k);
1157 }
1158 let mut r = T::one();
1159 let mut d = T::one();
1160 loop {
1161 if d > k {
1162 break;
1163 }
1164 r = multiply_and_divide(r, n.clone(), d.clone());
1165 n = n - T::one();
1166 d = d + T::one();
1167 }
1168 r
1169}
1170
1171pub fn multinomial<T: Integer + Clone>(k: &[T]) -> T
1173where
1174 for<'a> T: Add<&'a T, Output = T>,
1175{
1176 let mut r = T::one();
1177 let mut p = T::zero();
1178 for i in k {
1179 p = p + i;
1180 r = r * binomial(p.clone(), i.clone());
1181 }
1182 r
1183}
1184
1185#[test]
1186fn test_lcm_overflow() {
1187 macro_rules! check {
1188 ($t:ty, $x:expr, $y:expr, $r:expr) => {{
1189 let x: $t = $x;
1190 let y: $t = $y;
1191 let o = x.checked_mul(y);
1192 assert!(
1193 o.is_none(),
1194 "sanity checking that {} input {} * {} overflows",
1195 stringify!($t),
1196 x,
1197 y
1198 );
1199 assert_eq!(x.lcm(&y), $r);
1200 assert_eq!(y.lcm(&x), $r);
1201 }};
1202 }
1203
1204 check!(i64, 46656000000000000, 600, 46656000000000000);
1206
1207 check!(i8, 0x40, 0x04, 0x40);
1208 check!(u8, 0x80, 0x02, 0x80);
1209 check!(i16, 0x40_00, 0x04, 0x40_00);
1210 check!(u16, 0x80_00, 0x02, 0x80_00);
1211 check!(i32, 0x4000_0000, 0x04, 0x4000_0000);
1212 check!(u32, 0x8000_0000, 0x02, 0x8000_0000);
1213 check!(i64, 0x4000_0000_0000_0000, 0x04, 0x4000_0000_0000_0000);
1214 check!(u64, 0x8000_0000_0000_0000, 0x02, 0x8000_0000_0000_0000);
1215}
1216
1217#[test]
1218fn test_iter_binomial() {
1219 macro_rules! check_simple {
1220 ($t:ty) => {{
1221 let n: $t = 3;
1222 let expected = [1, 3, 3, 1];
1223 for (b, &e) in IterBinomial::new(n).zip(&expected) {
1224 assert_eq!(b, e);
1225 }
1226 }};
1227 }
1228
1229 check_simple!(u8);
1230 check_simple!(i8);
1231 check_simple!(u16);
1232 check_simple!(i16);
1233 check_simple!(u32);
1234 check_simple!(i32);
1235 check_simple!(u64);
1236 check_simple!(i64);
1237
1238 macro_rules! check_binomial {
1239 ($t:ty, $n:expr) => {{
1240 let n: $t = $n;
1241 let mut k: $t = 0;
1242 for b in IterBinomial::new(n) {
1243 assert_eq!(b, binomial(n, k));
1244 k += 1;
1245 }
1246 }};
1247 }
1248
1249 check_binomial!(u8, 10);
1251 check_binomial!(i8, 9);
1252 check_binomial!(u16, 18);
1253 check_binomial!(i16, 17);
1254 check_binomial!(u32, 34);
1255 check_binomial!(i32, 33);
1256 check_binomial!(u64, 67);
1257 check_binomial!(i64, 66);
1258}
1259
1260#[test]
1261fn test_binomial() {
1262 macro_rules! check {
1263 ($t:ty, $x:expr, $y:expr, $r:expr) => {{
1264 let x: $t = $x;
1265 let y: $t = $y;
1266 let expected: $t = $r;
1267 assert_eq!(binomial(x, y), expected);
1268 if y <= x {
1269 assert_eq!(binomial(x, x - y), expected);
1270 }
1271 }};
1272 }
1273 check!(u8, 9, 4, 126);
1274 check!(u8, 0, 0, 1);
1275 check!(u8, 2, 3, 0);
1276
1277 check!(i8, 9, 4, 126);
1278 check!(i8, 0, 0, 1);
1279 check!(i8, 2, 3, 0);
1280
1281 check!(u16, 100, 2, 4950);
1282 check!(u16, 14, 4, 1001);
1283 check!(u16, 0, 0, 1);
1284 check!(u16, 2, 3, 0);
1285
1286 check!(i16, 100, 2, 4950);
1287 check!(i16, 14, 4, 1001);
1288 check!(i16, 0, 0, 1);
1289 check!(i16, 2, 3, 0);
1290
1291 check!(u32, 100, 2, 4950);
1292 check!(u32, 35, 11, 417225900);
1293 check!(u32, 14, 4, 1001);
1294 check!(u32, 0, 0, 1);
1295 check!(u32, 2, 3, 0);
1296
1297 check!(i32, 100, 2, 4950);
1298 check!(i32, 35, 11, 417225900);
1299 check!(i32, 14, 4, 1001);
1300 check!(i32, 0, 0, 1);
1301 check!(i32, 2, 3, 0);
1302
1303 check!(u64, 100, 2, 4950);
1304 check!(u64, 35, 11, 417225900);
1305 check!(u64, 14, 4, 1001);
1306 check!(u64, 0, 0, 1);
1307 check!(u64, 2, 3, 0);
1308
1309 check!(i64, 100, 2, 4950);
1310 check!(i64, 35, 11, 417225900);
1311 check!(i64, 14, 4, 1001);
1312 check!(i64, 0, 0, 1);
1313 check!(i64, 2, 3, 0);
1314}
1315
1316#[test]
1317fn test_multinomial() {
1318 macro_rules! check_binomial {
1319 ($t:ty, $k:expr) => {{
1320 let n: $t = $k.iter().fold(0, |acc, &x| acc + x);
1321 let k: &[$t] = $k;
1322 assert_eq!(k.len(), 2);
1323 assert_eq!(multinomial(k), binomial(n, k[0]));
1324 }};
1325 }
1326
1327 check_binomial!(u8, &[4, 5]);
1328
1329 check_binomial!(i8, &[4, 5]);
1330
1331 check_binomial!(u16, &[2, 98]);
1332 check_binomial!(u16, &[4, 10]);
1333
1334 check_binomial!(i16, &[2, 98]);
1335 check_binomial!(i16, &[4, 10]);
1336
1337 check_binomial!(u32, &[2, 98]);
1338 check_binomial!(u32, &[11, 24]);
1339 check_binomial!(u32, &[4, 10]);
1340
1341 check_binomial!(i32, &[2, 98]);
1342 check_binomial!(i32, &[11, 24]);
1343 check_binomial!(i32, &[4, 10]);
1344
1345 check_binomial!(u64, &[2, 98]);
1346 check_binomial!(u64, &[11, 24]);
1347 check_binomial!(u64, &[4, 10]);
1348
1349 check_binomial!(i64, &[2, 98]);
1350 check_binomial!(i64, &[11, 24]);
1351 check_binomial!(i64, &[4, 10]);
1352
1353 macro_rules! check_multinomial {
1354 ($t:ty, $k:expr, $r:expr) => {{
1355 let k: &[$t] = $k;
1356 let expected: $t = $r;
1357 assert_eq!(multinomial(k), expected);
1358 }};
1359 }
1360
1361 check_multinomial!(u8, &[2, 1, 2], 30);
1362 check_multinomial!(u8, &[2, 3, 0], 10);
1363
1364 check_multinomial!(i8, &[2, 1, 2], 30);
1365 check_multinomial!(i8, &[2, 3, 0], 10);
1366
1367 check_multinomial!(u16, &[2, 1, 2], 30);
1368 check_multinomial!(u16, &[2, 3, 0], 10);
1369
1370 check_multinomial!(i16, &[2, 1, 2], 30);
1371 check_multinomial!(i16, &[2, 3, 0], 10);
1372
1373 check_multinomial!(u32, &[2, 1, 2], 30);
1374 check_multinomial!(u32, &[2, 3, 0], 10);
1375
1376 check_multinomial!(i32, &[2, 1, 2], 30);
1377 check_multinomial!(i32, &[2, 3, 0], 10);
1378
1379 check_multinomial!(u64, &[2, 1, 2], 30);
1380 check_multinomial!(u64, &[2, 3, 0], 10);
1381
1382 check_multinomial!(i64, &[2, 1, 2], 30);
1383 check_multinomial!(i64, &[2, 3, 0], 10);
1384
1385 check_multinomial!(u64, &[], 1);
1386 check_multinomial!(u64, &[0], 1);
1387 check_multinomial!(u64, &[12345], 1);
1388}