lib.rs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
  2. // file at the top-level directory of this distribution and at
  3. // http://rust-lang.org/COPYRIGHT.
  4. //
  5. // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
  6. // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
  7. // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
  8. // option. This file may not be copied, modified, or distributed
  9. // except according to those terms.
  10. //! Integer trait and functions.
  11. #![doc(html_logo_url = "https://rust-num.github.io/num/rust-logo-128x128-blk-v2.png",
  12. html_favicon_url = "https://rust-num.github.io/num/favicon.ico",
  13. html_root_url = "https://rust-num.github.io/num/",
  14. html_playground_url = "http://play.integer32.com/")]
  15. extern crate num_traits as traits;
  16. use std::ops::Add;
  17. use traits::{Num, Signed};
  18. pub trait Integer: Sized + Num + PartialOrd + Ord + Eq {
  19. /// Floored integer division.
  20. ///
  21. /// # Examples
  22. ///
  23. /// ~~~
  24. /// # use num_integer::Integer;
  25. /// assert!(( 8).div_floor(& 3) == 2);
  26. /// assert!(( 8).div_floor(&-3) == -3);
  27. /// assert!((-8).div_floor(& 3) == -3);
  28. /// assert!((-8).div_floor(&-3) == 2);
  29. ///
  30. /// assert!(( 1).div_floor(& 2) == 0);
  31. /// assert!(( 1).div_floor(&-2) == -1);
  32. /// assert!((-1).div_floor(& 2) == -1);
  33. /// assert!((-1).div_floor(&-2) == 0);
  34. /// ~~~
  35. fn div_floor(&self, other: &Self) -> Self;
  36. /// Floored integer modulo, satisfying:
  37. ///
  38. /// ~~~
  39. /// # use num_integer::Integer;
  40. /// # let n = 1; let d = 1;
  41. /// assert!(n.div_floor(&d) * d + n.mod_floor(&d) == n)
  42. /// ~~~
  43. ///
  44. /// # Examples
  45. ///
  46. /// ~~~
  47. /// # use num_integer::Integer;
  48. /// assert!(( 8).mod_floor(& 3) == 2);
  49. /// assert!(( 8).mod_floor(&-3) == -1);
  50. /// assert!((-8).mod_floor(& 3) == 1);
  51. /// assert!((-8).mod_floor(&-3) == -2);
  52. ///
  53. /// assert!(( 1).mod_floor(& 2) == 1);
  54. /// assert!(( 1).mod_floor(&-2) == -1);
  55. /// assert!((-1).mod_floor(& 2) == 1);
  56. /// assert!((-1).mod_floor(&-2) == -1);
  57. /// ~~~
  58. fn mod_floor(&self, other: &Self) -> Self;
  59. /// Greatest Common Divisor (GCD).
  60. ///
  61. /// # Examples
  62. ///
  63. /// ~~~
  64. /// # use num_integer::Integer;
  65. /// assert_eq!(6.gcd(&8), 2);
  66. /// assert_eq!(7.gcd(&3), 1);
  67. /// ~~~
  68. fn gcd(&self, other: &Self) -> Self;
  69. /// Lowest Common Multiple (LCM).
  70. ///
  71. /// # Examples
  72. ///
  73. /// ~~~
  74. /// # use num_integer::Integer;
  75. /// assert_eq!(7.lcm(&3), 21);
  76. /// assert_eq!(2.lcm(&4), 4);
  77. /// ~~~
  78. fn lcm(&self, other: &Self) -> Self;
  79. /// Deprecated, use `is_multiple_of` instead.
  80. fn divides(&self, other: &Self) -> bool;
  81. /// Returns `true` if `other` is a multiple of `self`.
  82. ///
  83. /// # Examples
  84. ///
  85. /// ~~~
  86. /// # use num_integer::Integer;
  87. /// assert_eq!(9.is_multiple_of(&3), true);
  88. /// assert_eq!(3.is_multiple_of(&9), false);
  89. /// ~~~
  90. fn is_multiple_of(&self, other: &Self) -> bool;
  91. /// Returns `true` if the number is even.
  92. ///
  93. /// # Examples
  94. ///
  95. /// ~~~
  96. /// # use num_integer::Integer;
  97. /// assert_eq!(3.is_even(), false);
  98. /// assert_eq!(4.is_even(), true);
  99. /// ~~~
  100. fn is_even(&self) -> bool;
  101. /// Returns `true` if the number is odd.
  102. ///
  103. /// # Examples
  104. ///
  105. /// ~~~
  106. /// # use num_integer::Integer;
  107. /// assert_eq!(3.is_odd(), true);
  108. /// assert_eq!(4.is_odd(), false);
  109. /// ~~~
  110. fn is_odd(&self) -> bool;
  111. /// Simultaneous truncated integer division and modulus.
  112. /// Returns `(quotient, remainder)`.
  113. ///
  114. /// # Examples
  115. ///
  116. /// ~~~
  117. /// # use num_integer::Integer;
  118. /// assert_eq!(( 8).div_rem( &3), ( 2, 2));
  119. /// assert_eq!(( 8).div_rem(&-3), (-2, 2));
  120. /// assert_eq!((-8).div_rem( &3), (-2, -2));
  121. /// assert_eq!((-8).div_rem(&-3), ( 2, -2));
  122. ///
  123. /// assert_eq!(( 1).div_rem( &2), ( 0, 1));
  124. /// assert_eq!(( 1).div_rem(&-2), ( 0, 1));
  125. /// assert_eq!((-1).div_rem( &2), ( 0, -1));
  126. /// assert_eq!((-1).div_rem(&-2), ( 0, -1));
  127. /// ~~~
  128. #[inline]
  129. fn div_rem(&self, other: &Self) -> (Self, Self);
  130. /// Simultaneous floored integer division and modulus.
  131. /// Returns `(quotient, remainder)`.
  132. ///
  133. /// # Examples
  134. ///
  135. /// ~~~
  136. /// # use num_integer::Integer;
  137. /// assert_eq!(( 8).div_mod_floor( &3), ( 2, 2));
  138. /// assert_eq!(( 8).div_mod_floor(&-3), (-3, -1));
  139. /// assert_eq!((-8).div_mod_floor( &3), (-3, 1));
  140. /// assert_eq!((-8).div_mod_floor(&-3), ( 2, -2));
  141. ///
  142. /// assert_eq!(( 1).div_mod_floor( &2), ( 0, 1));
  143. /// assert_eq!(( 1).div_mod_floor(&-2), (-1, -1));
  144. /// assert_eq!((-1).div_mod_floor( &2), (-1, 1));
  145. /// assert_eq!((-1).div_mod_floor(&-2), ( 0, -1));
  146. /// ~~~
  147. fn div_mod_floor(&self, other: &Self) -> (Self, Self) {
  148. (self.div_floor(other), self.mod_floor(other))
  149. }
  150. }
  151. /// Simultaneous integer division and modulus
  152. #[inline]
  153. pub fn div_rem<T: Integer>(x: T, y: T) -> (T, T) {
  154. x.div_rem(&y)
  155. }
  156. /// Floored integer division
  157. #[inline]
  158. pub fn div_floor<T: Integer>(x: T, y: T) -> T {
  159. x.div_floor(&y)
  160. }
  161. /// Floored integer modulus
  162. #[inline]
  163. pub fn mod_floor<T: Integer>(x: T, y: T) -> T {
  164. x.mod_floor(&y)
  165. }
  166. /// Simultaneous floored integer division and modulus
  167. #[inline]
  168. pub fn div_mod_floor<T: Integer>(x: T, y: T) -> (T, T) {
  169. x.div_mod_floor(&y)
  170. }
  171. /// Calculates the Greatest Common Divisor (GCD) of the number and `other`. The
  172. /// result is always positive.
  173. #[inline(always)]
  174. pub fn gcd<T: Integer>(x: T, y: T) -> T {
  175. x.gcd(&y)
  176. }
  177. /// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
  178. #[inline(always)]
  179. pub fn lcm<T: Integer>(x: T, y: T) -> T {
  180. x.lcm(&y)
  181. }
  182. macro_rules! impl_integer_for_isize {
  183. ($T:ty, $test_mod:ident) => (
  184. impl Integer for $T {
  185. /// Floored integer division
  186. #[inline]
  187. fn div_floor(&self, other: &Self) -> Self {
  188. // Algorithm from [Daan Leijen. _Division and Modulus for Computer Scientists_,
  189. // December 2001](http://research.microsoft.com/pubs/151917/divmodnote-letter.pdf)
  190. match self.div_rem(other) {
  191. (d, r) if (r > 0 && *other < 0)
  192. || (r < 0 && *other > 0) => d - 1,
  193. (d, _) => d,
  194. }
  195. }
  196. /// Floored integer modulo
  197. #[inline]
  198. fn mod_floor(&self, other: &Self) -> Self {
  199. // Algorithm from [Daan Leijen. _Division and Modulus for Computer Scientists_,
  200. // December 2001](http://research.microsoft.com/pubs/151917/divmodnote-letter.pdf)
  201. match *self % *other {
  202. r if (r > 0 && *other < 0)
  203. || (r < 0 && *other > 0) => r + *other,
  204. r => r,
  205. }
  206. }
  207. /// Calculates `div_floor` and `mod_floor` simultaneously
  208. #[inline]
  209. fn div_mod_floor(&self, other: &Self) -> (Self, Self) {
  210. // Algorithm from [Daan Leijen. _Division and Modulus for Computer Scientists_,
  211. // December 2001](http://research.microsoft.com/pubs/151917/divmodnote-letter.pdf)
  212. match self.div_rem(other) {
  213. (d, r) if (r > 0 && *other < 0)
  214. || (r < 0 && *other > 0) => (d - 1, r + *other),
  215. (d, r) => (d, r),
  216. }
  217. }
  218. /// Calculates the Greatest Common Divisor (GCD) of the number and
  219. /// `other`. The result is always positive.
  220. #[inline]
  221. fn gcd(&self, other: &Self) -> Self {
  222. // Use Stein's algorithm
  223. let mut m = *self;
  224. let mut n = *other;
  225. if m == 0 || n == 0 { return (m | n).abs() }
  226. // find common factors of 2
  227. let shift = (m | n).trailing_zeros();
  228. // The algorithm needs positive numbers, but the minimum value
  229. // can't be represented as a positive one.
  230. // It's also a power of two, so the gcd can be
  231. // calculated by bitshifting in that case
  232. // Assuming two's complement, the number created by the shift
  233. // is positive for all numbers except gcd = abs(min value)
  234. // The call to .abs() causes a panic in debug mode
  235. if m == Self::min_value() || n == Self::min_value() {
  236. return (1 << shift).abs()
  237. }
  238. // guaranteed to be positive now, rest like unsigned algorithm
  239. m = m.abs();
  240. n = n.abs();
  241. // divide n and m by 2 until odd
  242. // m inside loop
  243. n >>= n.trailing_zeros();
  244. while m != 0 {
  245. m >>= m.trailing_zeros();
  246. if n > m { ::std::mem::swap(&mut n, &mut m) }
  247. m -= n;
  248. }
  249. n << shift
  250. }
  251. /// Calculates the Lowest Common Multiple (LCM) of the number and
  252. /// `other`.
  253. #[inline]
  254. fn lcm(&self, other: &Self) -> Self {
  255. // should not have to recalculate abs
  256. (*self * (*other / self.gcd(other))).abs()
  257. }
  258. /// Deprecated, use `is_multiple_of` instead.
  259. #[inline]
  260. fn divides(&self, other: &Self) -> bool {
  261. self.is_multiple_of(other)
  262. }
  263. /// Returns `true` if the number is a multiple of `other`.
  264. #[inline]
  265. fn is_multiple_of(&self, other: &Self) -> bool {
  266. *self % *other == 0
  267. }
  268. /// Returns `true` if the number is divisible by `2`
  269. #[inline]
  270. fn is_even(&self) -> bool { (*self) & 1 == 0 }
  271. /// Returns `true` if the number is not divisible by `2`
  272. #[inline]
  273. fn is_odd(&self) -> bool { !self.is_even() }
  274. /// Simultaneous truncated integer division and modulus.
  275. #[inline]
  276. fn div_rem(&self, other: &Self) -> (Self, Self) {
  277. (*self / *other, *self % *other)
  278. }
  279. }
  280. #[cfg(test)]
  281. mod $test_mod {
  282. use Integer;
  283. /// Checks that the division rule holds for:
  284. ///
  285. /// - `n`: numerator (dividend)
  286. /// - `d`: denominator (divisor)
  287. /// - `qr`: quotient and remainder
  288. #[cfg(test)]
  289. fn test_division_rule((n,d): ($T, $T), (q,r): ($T, $T)) {
  290. assert_eq!(d * q + r, n);
  291. }
  292. #[test]
  293. fn test_div_rem() {
  294. fn test_nd_dr(nd: ($T,$T), qr: ($T,$T)) {
  295. let (n,d) = nd;
  296. let separate_div_rem = (n / d, n % d);
  297. let combined_div_rem = n.div_rem(&d);
  298. assert_eq!(separate_div_rem, qr);
  299. assert_eq!(combined_div_rem, qr);
  300. test_division_rule(nd, separate_div_rem);
  301. test_division_rule(nd, combined_div_rem);
  302. }
  303. test_nd_dr(( 8, 3), ( 2, 2));
  304. test_nd_dr(( 8, -3), (-2, 2));
  305. test_nd_dr((-8, 3), (-2, -2));
  306. test_nd_dr((-8, -3), ( 2, -2));
  307. test_nd_dr(( 1, 2), ( 0, 1));
  308. test_nd_dr(( 1, -2), ( 0, 1));
  309. test_nd_dr((-1, 2), ( 0, -1));
  310. test_nd_dr((-1, -2), ( 0, -1));
  311. }
  312. #[test]
  313. fn test_div_mod_floor() {
  314. fn test_nd_dm(nd: ($T,$T), dm: ($T,$T)) {
  315. let (n,d) = nd;
  316. let separate_div_mod_floor = (n.div_floor(&d), n.mod_floor(&d));
  317. let combined_div_mod_floor = n.div_mod_floor(&d);
  318. assert_eq!(separate_div_mod_floor, dm);
  319. assert_eq!(combined_div_mod_floor, dm);
  320. test_division_rule(nd, separate_div_mod_floor);
  321. test_division_rule(nd, combined_div_mod_floor);
  322. }
  323. test_nd_dm(( 8, 3), ( 2, 2));
  324. test_nd_dm(( 8, -3), (-3, -1));
  325. test_nd_dm((-8, 3), (-3, 1));
  326. test_nd_dm((-8, -3), ( 2, -2));
  327. test_nd_dm(( 1, 2), ( 0, 1));
  328. test_nd_dm(( 1, -2), (-1, -1));
  329. test_nd_dm((-1, 2), (-1, 1));
  330. test_nd_dm((-1, -2), ( 0, -1));
  331. }
  332. #[test]
  333. fn test_gcd() {
  334. assert_eq!((10 as $T).gcd(&2), 2 as $T);
  335. assert_eq!((10 as $T).gcd(&3), 1 as $T);
  336. assert_eq!((0 as $T).gcd(&3), 3 as $T);
  337. assert_eq!((3 as $T).gcd(&3), 3 as $T);
  338. assert_eq!((56 as $T).gcd(&42), 14 as $T);
  339. assert_eq!((3 as $T).gcd(&-3), 3 as $T);
  340. assert_eq!((-6 as $T).gcd(&3), 3 as $T);
  341. assert_eq!((-4 as $T).gcd(&-2), 2 as $T);
  342. }
  343. #[test]
  344. fn test_gcd_cmp_with_euclidean() {
  345. fn euclidean_gcd(mut m: $T, mut n: $T) -> $T {
  346. while m != 0 {
  347. ::std::mem::swap(&mut m, &mut n);
  348. m %= n;
  349. }
  350. n.abs()
  351. }
  352. // gcd(-128, b) = 128 is not representable as positive value
  353. // for i8
  354. for i in -127..127 {
  355. for j in -127..127 {
  356. assert_eq!(euclidean_gcd(i,j), i.gcd(&j));
  357. }
  358. }
  359. // last value
  360. // FIXME: Use inclusive ranges for above loop when implemented
  361. let i = 127;
  362. for j in -127..127 {
  363. assert_eq!(euclidean_gcd(i,j), i.gcd(&j));
  364. }
  365. assert_eq!(127.gcd(&127), 127);
  366. }
  367. #[test]
  368. fn test_gcd_min_val() {
  369. let min = <$T>::min_value();
  370. let max = <$T>::max_value();
  371. let max_pow2 = max / 2 + 1;
  372. assert_eq!(min.gcd(&max), 1 as $T);
  373. assert_eq!(max.gcd(&min), 1 as $T);
  374. assert_eq!(min.gcd(&max_pow2), max_pow2);
  375. assert_eq!(max_pow2.gcd(&min), max_pow2);
  376. assert_eq!(min.gcd(&42), 2 as $T);
  377. assert_eq!((42 as $T).gcd(&min), 2 as $T);
  378. }
  379. #[test]
  380. #[should_panic]
  381. fn test_gcd_min_val_min_val() {
  382. let min = <$T>::min_value();
  383. assert!(min.gcd(&min) >= 0);
  384. }
  385. #[test]
  386. #[should_panic]
  387. fn test_gcd_min_val_0() {
  388. let min = <$T>::min_value();
  389. assert!(min.gcd(&0) >= 0);
  390. }
  391. #[test]
  392. #[should_panic]
  393. fn test_gcd_0_min_val() {
  394. let min = <$T>::min_value();
  395. assert!((0 as $T).gcd(&min) >= 0);
  396. }
  397. #[test]
  398. fn test_lcm() {
  399. assert_eq!((1 as $T).lcm(&0), 0 as $T);
  400. assert_eq!((0 as $T).lcm(&1), 0 as $T);
  401. assert_eq!((1 as $T).lcm(&1), 1 as $T);
  402. assert_eq!((-1 as $T).lcm(&1), 1 as $T);
  403. assert_eq!((1 as $T).lcm(&-1), 1 as $T);
  404. assert_eq!((-1 as $T).lcm(&-1), 1 as $T);
  405. assert_eq!((8 as $T).lcm(&9), 72 as $T);
  406. assert_eq!((11 as $T).lcm(&5), 55 as $T);
  407. }
  408. #[test]
  409. fn test_even() {
  410. assert_eq!((-4 as $T).is_even(), true);
  411. assert_eq!((-3 as $T).is_even(), false);
  412. assert_eq!((-2 as $T).is_even(), true);
  413. assert_eq!((-1 as $T).is_even(), false);
  414. assert_eq!((0 as $T).is_even(), true);
  415. assert_eq!((1 as $T).is_even(), false);
  416. assert_eq!((2 as $T).is_even(), true);
  417. assert_eq!((3 as $T).is_even(), false);
  418. assert_eq!((4 as $T).is_even(), true);
  419. }
  420. #[test]
  421. fn test_odd() {
  422. assert_eq!((-4 as $T).is_odd(), false);
  423. assert_eq!((-3 as $T).is_odd(), true);
  424. assert_eq!((-2 as $T).is_odd(), false);
  425. assert_eq!((-1 as $T).is_odd(), true);
  426. assert_eq!((0 as $T).is_odd(), false);
  427. assert_eq!((1 as $T).is_odd(), true);
  428. assert_eq!((2 as $T).is_odd(), false);
  429. assert_eq!((3 as $T).is_odd(), true);
  430. assert_eq!((4 as $T).is_odd(), false);
  431. }
  432. }
  433. )
  434. }
  435. impl_integer_for_isize!(i8, test_integer_i8);
  436. impl_integer_for_isize!(i16, test_integer_i16);
  437. impl_integer_for_isize!(i32, test_integer_i32);
  438. impl_integer_for_isize!(i64, test_integer_i64);
  439. impl_integer_for_isize!(isize, test_integer_isize);
  440. macro_rules! impl_integer_for_usize {
  441. ($T:ty, $test_mod:ident) => (
  442. impl Integer for $T {
  443. /// Unsigned integer division. Returns the same result as `div` (`/`).
  444. #[inline]
  445. fn div_floor(&self, other: &Self) -> Self {
  446. *self / *other
  447. }
  448. /// Unsigned integer modulo operation. Returns the same result as `rem` (`%`).
  449. #[inline]
  450. fn mod_floor(&self, other: &Self) -> Self {
  451. *self % *other
  452. }
  453. /// Calculates the Greatest Common Divisor (GCD) of the number and `other`
  454. #[inline]
  455. fn gcd(&self, other: &Self) -> Self {
  456. // Use Stein's algorithm
  457. let mut m = *self;
  458. let mut n = *other;
  459. if m == 0 || n == 0 { return m | n }
  460. // find common factors of 2
  461. let shift = (m | n).trailing_zeros();
  462. // divide n and m by 2 until odd
  463. // m inside loop
  464. n >>= n.trailing_zeros();
  465. while m != 0 {
  466. m >>= m.trailing_zeros();
  467. if n > m { ::std::mem::swap(&mut n, &mut m) }
  468. m -= n;
  469. }
  470. n << shift
  471. }
  472. /// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
  473. #[inline]
  474. fn lcm(&self, other: &Self) -> Self {
  475. *self * (*other / self.gcd(other))
  476. }
  477. /// Deprecated, use `is_multiple_of` instead.
  478. #[inline]
  479. fn divides(&self, other: &Self) -> bool {
  480. self.is_multiple_of(other)
  481. }
  482. /// Returns `true` if the number is a multiple of `other`.
  483. #[inline]
  484. fn is_multiple_of(&self, other: &Self) -> bool {
  485. *self % *other == 0
  486. }
  487. /// Returns `true` if the number is divisible by `2`.
  488. #[inline]
  489. fn is_even(&self) -> bool {
  490. *self % 2 == 0
  491. }
  492. /// Returns `true` if the number is not divisible by `2`.
  493. #[inline]
  494. fn is_odd(&self) -> bool {
  495. !self.is_even()
  496. }
  497. /// Simultaneous truncated integer division and modulus.
  498. #[inline]
  499. fn div_rem(&self, other: &Self) -> (Self, Self) {
  500. (*self / *other, *self % *other)
  501. }
  502. }
  503. #[cfg(test)]
  504. mod $test_mod {
  505. use Integer;
  506. #[test]
  507. fn test_div_mod_floor() {
  508. assert_eq!((10 as $T).div_floor(&(3 as $T)), 3 as $T);
  509. assert_eq!((10 as $T).mod_floor(&(3 as $T)), 1 as $T);
  510. assert_eq!((10 as $T).div_mod_floor(&(3 as $T)), (3 as $T, 1 as $T));
  511. assert_eq!((5 as $T).div_floor(&(5 as $T)), 1 as $T);
  512. assert_eq!((5 as $T).mod_floor(&(5 as $T)), 0 as $T);
  513. assert_eq!((5 as $T).div_mod_floor(&(5 as $T)), (1 as $T, 0 as $T));
  514. assert_eq!((3 as $T).div_floor(&(7 as $T)), 0 as $T);
  515. assert_eq!((3 as $T).mod_floor(&(7 as $T)), 3 as $T);
  516. assert_eq!((3 as $T).div_mod_floor(&(7 as $T)), (0 as $T, 3 as $T));
  517. }
  518. #[test]
  519. fn test_gcd() {
  520. assert_eq!((10 as $T).gcd(&2), 2 as $T);
  521. assert_eq!((10 as $T).gcd(&3), 1 as $T);
  522. assert_eq!((0 as $T).gcd(&3), 3 as $T);
  523. assert_eq!((3 as $T).gcd(&3), 3 as $T);
  524. assert_eq!((56 as $T).gcd(&42), 14 as $T);
  525. }
  526. #[test]
  527. fn test_gcd_cmp_with_euclidean() {
  528. fn euclidean_gcd(mut m: $T, mut n: $T) -> $T {
  529. while m != 0 {
  530. ::std::mem::swap(&mut m, &mut n);
  531. m %= n;
  532. }
  533. n
  534. }
  535. for i in 0..255 {
  536. for j in 0..255 {
  537. assert_eq!(euclidean_gcd(i,j), i.gcd(&j));
  538. }
  539. }
  540. // last value
  541. // FIXME: Use inclusive ranges for above loop when implemented
  542. let i = 255;
  543. for j in 0..255 {
  544. assert_eq!(euclidean_gcd(i,j), i.gcd(&j));
  545. }
  546. assert_eq!(255.gcd(&255), 255);
  547. }
  548. #[test]
  549. fn test_lcm() {
  550. assert_eq!((1 as $T).lcm(&0), 0 as $T);
  551. assert_eq!((0 as $T).lcm(&1), 0 as $T);
  552. assert_eq!((1 as $T).lcm(&1), 1 as $T);
  553. assert_eq!((8 as $T).lcm(&9), 72 as $T);
  554. assert_eq!((11 as $T).lcm(&5), 55 as $T);
  555. assert_eq!((15 as $T).lcm(&17), 255 as $T);
  556. }
  557. #[test]
  558. fn test_is_multiple_of() {
  559. assert!((6 as $T).is_multiple_of(&(6 as $T)));
  560. assert!((6 as $T).is_multiple_of(&(3 as $T)));
  561. assert!((6 as $T).is_multiple_of(&(1 as $T)));
  562. }
  563. #[test]
  564. fn test_even() {
  565. assert_eq!((0 as $T).is_even(), true);
  566. assert_eq!((1 as $T).is_even(), false);
  567. assert_eq!((2 as $T).is_even(), true);
  568. assert_eq!((3 as $T).is_even(), false);
  569. assert_eq!((4 as $T).is_even(), true);
  570. }
  571. #[test]
  572. fn test_odd() {
  573. assert_eq!((0 as $T).is_odd(), false);
  574. assert_eq!((1 as $T).is_odd(), true);
  575. assert_eq!((2 as $T).is_odd(), false);
  576. assert_eq!((3 as $T).is_odd(), true);
  577. assert_eq!((4 as $T).is_odd(), false);
  578. }
  579. }
  580. )
  581. }
  582. impl_integer_for_usize!(u8, test_integer_u8);
  583. impl_integer_for_usize!(u16, test_integer_u16);
  584. impl_integer_for_usize!(u32, test_integer_u32);
  585. impl_integer_for_usize!(u64, test_integer_u64);
  586. impl_integer_for_usize!(usize, test_integer_usize);
  587. /// Calculate r * a / b, avoiding overflows and fractions.
  588. fn multiply_and_divide<T: Integer + Clone>(r: T, a: T, b: T) -> T {
  589. // See http://blog.plover.com/math/choose-2.html for the idea.
  590. let g = gcd(r.clone(), b.clone());
  591. (r/g.clone() * a) / (b/g)
  592. }
  593. /// Calculate the binomial coefficient.
  594. pub fn binomial<T: Integer + Clone>(mut n: T, k: T) -> T {
  595. // See http://blog.plover.com/math/choose.html for the idea.
  596. if k > n {
  597. return T::zero();
  598. }
  599. if k > n.clone() - k.clone() {
  600. return binomial(n.clone(), n - k);
  601. }
  602. let mut r = T::one();
  603. let mut d = T::one();
  604. loop {
  605. if d > k {
  606. break;
  607. }
  608. r = multiply_and_divide(r, n.clone(), d.clone());
  609. n = n - T::one();
  610. d = d + T::one();
  611. }
  612. r
  613. }
  614. /// Calculate the multinomial coefficient.
  615. pub fn multinomial<T: Integer + Clone>(k: &[T]) -> T
  616. where for<'a> T: Add<&'a T, Output = T>
  617. {
  618. let mut r = T::one();
  619. let mut p = T::zero();
  620. for i in k {
  621. p = p + i;
  622. r = r * binomial(p.clone(), i.clone());
  623. }
  624. r
  625. }
  626. #[test]
  627. fn test_lcm_overflow() {
  628. macro_rules! check {
  629. ($t:ty, $x:expr, $y:expr, $r:expr) => { {
  630. let x: $t = $x;
  631. let y: $t = $y;
  632. let o = x.checked_mul(y);
  633. assert!(o.is_none(),
  634. "sanity checking that {} input {} * {} overflows",
  635. stringify!($t), x, y);
  636. assert_eq!(x.lcm(&y), $r);
  637. assert_eq!(y.lcm(&x), $r);
  638. } }
  639. }
  640. // Original bug (Issue #166)
  641. check!(i64, 46656000000000000, 600, 46656000000000000);
  642. check!(i8, 0x40, 0x04, 0x40);
  643. check!(u8, 0x80, 0x02, 0x80);
  644. check!(i16, 0x40_00, 0x04, 0x40_00);
  645. check!(u16, 0x80_00, 0x02, 0x80_00);
  646. check!(i32, 0x4000_0000, 0x04, 0x4000_0000);
  647. check!(u32, 0x8000_0000, 0x02, 0x8000_0000);
  648. check!(i64, 0x4000_0000_0000_0000, 0x04, 0x4000_0000_0000_0000);
  649. check!(u64, 0x8000_0000_0000_0000, 0x02, 0x8000_0000_0000_0000);
  650. }
  651. #[test]
  652. fn test_binomial() {
  653. macro_rules! check {
  654. ($t:ty, $x:expr, $y:expr, $r:expr) => { {
  655. let x: $t = $x;
  656. let y: $t = $y;
  657. let expected: $t = $r;
  658. assert_eq!(binomial(x, y), expected);
  659. if y <= x {
  660. assert_eq!(binomial(x, x - y), expected);
  661. }
  662. } }
  663. }
  664. check!(u8, 9, 4, 126);
  665. check!(u8, 0, 0, 1);
  666. check!(u8, 2, 3, 0);
  667. check!(i8, 9, 4, 126);
  668. check!(i8, 0, 0, 1);
  669. check!(i8, 2, 3, 0);
  670. check!(u16, 100, 2, 4950);
  671. check!(u16, 14, 4, 1001);
  672. check!(u16, 0, 0, 1);
  673. check!(u16, 2, 3, 0);
  674. check!(i16, 100, 2, 4950);
  675. check!(i16, 14, 4, 1001);
  676. check!(i16, 0, 0, 1);
  677. check!(i16, 2, 3, 0);
  678. check!(u32, 100, 2, 4950);
  679. check!(u32, 35, 11, 417225900);
  680. check!(u32, 14, 4, 1001);
  681. check!(u32, 0, 0, 1);
  682. check!(u32, 2, 3, 0);
  683. check!(i32, 100, 2, 4950);
  684. check!(i32, 35, 11, 417225900);
  685. check!(i32, 14, 4, 1001);
  686. check!(i32, 0, 0, 1);
  687. check!(i32, 2, 3, 0);
  688. check!(u64, 100, 2, 4950);
  689. check!(u64, 35, 11, 417225900);
  690. check!(u64, 14, 4, 1001);
  691. check!(u64, 0, 0, 1);
  692. check!(u64, 2, 3, 0);
  693. check!(i64, 100, 2, 4950);
  694. check!(i64, 35, 11, 417225900);
  695. check!(i64, 14, 4, 1001);
  696. check!(i64, 0, 0, 1);
  697. check!(i64, 2, 3, 0);
  698. }
  699. #[test]
  700. fn test_multinomial() {
  701. macro_rules! check_binomial {
  702. ($t:ty, $k:expr) => { {
  703. let n: $t = $k.iter().fold(0, |acc, &x| acc + x);
  704. let k: &[$t] = $k;
  705. assert_eq!(k.len(), 2);
  706. assert_eq!(multinomial(k), binomial(n, k[0]));
  707. } }
  708. }
  709. check_binomial!(u8, &[4, 5]);
  710. check_binomial!(i8, &[4, 5]);
  711. check_binomial!(u16, &[2, 98]);
  712. check_binomial!(u16, &[4, 10]);
  713. check_binomial!(i16, &[2, 98]);
  714. check_binomial!(i16, &[4, 10]);
  715. check_binomial!(u32, &[2, 98]);
  716. check_binomial!(u32, &[11, 24]);
  717. check_binomial!(u32, &[4, 10]);
  718. check_binomial!(i32, &[2, 98]);
  719. check_binomial!(i32, &[11, 24]);
  720. check_binomial!(i32, &[4, 10]);
  721. check_binomial!(u64, &[2, 98]);
  722. check_binomial!(u64, &[11, 24]);
  723. check_binomial!(u64, &[4, 10]);
  724. check_binomial!(i64, &[2, 98]);
  725. check_binomial!(i64, &[11, 24]);
  726. check_binomial!(i64, &[4, 10]);
  727. macro_rules! check_multinomial {
  728. ($t:ty, $k:expr, $r:expr) => { {
  729. let k: &[$t] = $k;
  730. let expected: $t = $r;
  731. assert_eq!(multinomial(k), expected);
  732. } }
  733. }
  734. check_multinomial!(u8, &[2, 1, 2], 30);
  735. check_multinomial!(u8, &[2, 3, 0], 10);
  736. check_multinomial!(i8, &[2, 1, 2], 30);
  737. check_multinomial!(i8, &[2, 3, 0], 10);
  738. check_multinomial!(u16, &[2, 1, 2], 30);
  739. check_multinomial!(u16, &[2, 3, 0], 10);
  740. check_multinomial!(i16, &[2, 1, 2], 30);
  741. check_multinomial!(i16, &[2, 3, 0], 10);
  742. check_multinomial!(u32, &[2, 1, 2], 30);
  743. check_multinomial!(u32, &[2, 3, 0], 10);
  744. check_multinomial!(i32, &[2, 1, 2], 30);
  745. check_multinomial!(i32, &[2, 3, 0], 10);
  746. check_multinomial!(u64, &[2, 1, 2], 30);
  747. check_multinomial!(u64, &[2, 3, 0], 10);
  748. check_multinomial!(i64, &[2, 1, 2], 30);
  749. check_multinomial!(i64, &[2, 3, 0], 10);
  750. check_multinomial!(u64, &[], 1);
  751. check_multinomial!(u64, &[0], 1);
  752. check_multinomial!(u64, &[12345], 1);
  753. }