lib.rs 28 KB

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