bigint.rs 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941
  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. //! A Big integer (signed version: `BigInt`, unsigned version: `BigUint`).
  11. //!
  12. //! A `BigUint` is represented as an array of `BigDigit`s.
  13. //! A `BigInt` is a combination of `BigUint` and `Sign`.
  14. //!
  15. //! Common numerical operations are overloaded, so we can treat them
  16. //! the same way we treat other numbers.
  17. //!
  18. //! ## Example
  19. //!
  20. //! ```rust
  21. //! use num::bigint::BigUint;
  22. //! use std::num::{Zero, One};
  23. //! use std::mem::replace;
  24. //!
  25. //! // Calculate large fibonacci numbers.
  26. //! fn fib(n: uint) -> BigUint {
  27. //! let mut f0: BigUint = Zero::zero();
  28. //! let mut f1: BigUint = One::one();
  29. //! for _ in range(0, n) {
  30. //! let f2 = f0 + f1;
  31. //! // This is a low cost way of swapping f0 with f1 and f1 with f2.
  32. //! f0 = replace(&mut f1, f2);
  33. //! }
  34. //! f0
  35. //! }
  36. //!
  37. //! // This is a very large number.
  38. //! println!("fib(1000) = {}", fib(1000));
  39. //! ```
  40. //!
  41. //! It's easy to generate large random numbers:
  42. //!
  43. //! ```rust
  44. //! use num::bigint::{ToBigInt, RandBigInt};
  45. //! use std::rand;
  46. //!
  47. //! let mut rng = rand::task_rng();
  48. //! let a = rng.gen_bigint(1000u);
  49. //!
  50. //! let low = -10000i.to_bigint().unwrap();
  51. //! let high = 10000i.to_bigint().unwrap();
  52. //! let b = rng.gen_bigint_range(&low, &high);
  53. //!
  54. //! // Probably an even larger number.
  55. //! println!("{}", a * b);
  56. //! ```
  57. use Integer;
  58. use rand::Rng;
  59. use std::{cmp, fmt, hash};
  60. use std::default::Default;
  61. use std::from_str::FromStr;
  62. use std::num::CheckedDiv;
  63. use std::num::{ToPrimitive, FromPrimitive};
  64. use std::num::{Zero, One, FromStrRadix};
  65. use std::str;
  66. use std::string::String;
  67. use std::{i64, u64};
  68. /// A `BigDigit` is a `BigUint`'s composing element.
  69. pub type BigDigit = u32;
  70. /// A `DoubleBigDigit` is the internal type used to do the computations. Its
  71. /// size is the double of the size of `BigDigit`.
  72. pub type DoubleBigDigit = u64;
  73. pub const ZERO_BIG_DIGIT: BigDigit = 0;
  74. static ZERO_VEC: [BigDigit, ..1] = [ZERO_BIG_DIGIT];
  75. #[allow(non_snake_case)]
  76. pub mod BigDigit {
  77. use super::BigDigit;
  78. use super::DoubleBigDigit;
  79. // `DoubleBigDigit` size dependent
  80. pub const BITS: uint = 32;
  81. pub const BASE: DoubleBigDigit = 1 << BITS;
  82. const LO_MASK: DoubleBigDigit = (-1 as DoubleBigDigit) >> BITS;
  83. #[inline]
  84. fn get_hi(n: DoubleBigDigit) -> BigDigit { (n >> BITS) as BigDigit }
  85. #[inline]
  86. fn get_lo(n: DoubleBigDigit) -> BigDigit { (n & LO_MASK) as BigDigit }
  87. /// Split one `DoubleBigDigit` into two `BigDigit`s.
  88. #[inline]
  89. pub fn from_doublebigdigit(n: DoubleBigDigit) -> (BigDigit, BigDigit) {
  90. (get_hi(n), get_lo(n))
  91. }
  92. /// Join two `BigDigit`s into one `DoubleBigDigit`
  93. #[inline]
  94. pub fn to_doublebigdigit(hi: BigDigit, lo: BigDigit) -> DoubleBigDigit {
  95. (lo as DoubleBigDigit) | ((hi as DoubleBigDigit) << BITS)
  96. }
  97. }
  98. /// A big unsigned integer type.
  99. ///
  100. /// A `BigUint`-typed value `BigUint { data: vec!(a, b, c) }` represents a number
  101. /// `(a + b * BigDigit::BASE + c * BigDigit::BASE^2)`.
  102. #[deriving(Clone)]
  103. pub struct BigUint {
  104. data: Vec<BigDigit>
  105. }
  106. impl PartialEq for BigUint {
  107. #[inline]
  108. fn eq(&self, other: &BigUint) -> bool {
  109. match self.cmp(other) { Equal => true, _ => false }
  110. }
  111. }
  112. impl Eq for BigUint {}
  113. impl PartialOrd for BigUint {
  114. #[inline]
  115. fn partial_cmp(&self, other: &BigUint) -> Option<Ordering> {
  116. Some(self.cmp(other))
  117. }
  118. }
  119. impl Ord for BigUint {
  120. #[inline]
  121. fn cmp(&self, other: &BigUint) -> Ordering {
  122. let (s_len, o_len) = (self.data.len(), other.data.len());
  123. if s_len < o_len { return Less; }
  124. if s_len > o_len { return Greater; }
  125. for (&self_i, &other_i) in self.data.iter().rev().zip(other.data.iter().rev()) {
  126. if self_i < other_i { return Less; }
  127. if self_i > other_i { return Greater; }
  128. }
  129. return Equal;
  130. }
  131. }
  132. impl Default for BigUint {
  133. #[inline]
  134. fn default() -> BigUint { Zero::zero() }
  135. }
  136. impl<S: hash::Writer> hash::Hash<S> for BigUint {
  137. fn hash(&self, state: &mut S) {
  138. // hash 0 in case it's all 0's
  139. 0u32.hash(state);
  140. let mut found_first_value = false;
  141. for elem in self.data.iter().rev() {
  142. // don't hash any leading 0's, they shouldn't affect the hash
  143. if found_first_value || *elem != 0 {
  144. found_first_value = true;
  145. elem.hash(state);
  146. }
  147. }
  148. }
  149. }
  150. impl fmt::Show for BigUint {
  151. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  152. write!(f, "{}", to_str_radix(self, 10))
  153. }
  154. }
  155. impl FromStr for BigUint {
  156. #[inline]
  157. fn from_str(s: &str) -> Option<BigUint> {
  158. FromStrRadix::from_str_radix(s, 10)
  159. }
  160. }
  161. impl Num for BigUint {}
  162. impl BitAnd<BigUint, BigUint> for BigUint {
  163. fn bitand(&self, other: &BigUint) -> BigUint {
  164. BigUint::new(self.data.iter().zip(other.data.iter()).map(|(ai, bi)| *ai & *bi).collect())
  165. }
  166. }
  167. impl BitOr<BigUint, BigUint> for BigUint {
  168. fn bitor(&self, other: &BigUint) -> BigUint {
  169. let zeros = ZERO_VEC.iter().cycle();
  170. let (a, b) = if self.data.len() > other.data.len() { (self, other) } else { (other, self) };
  171. let ored = a.data.iter().zip(b.data.iter().chain(zeros)).map(
  172. |(ai, bi)| *ai | *bi
  173. ).collect();
  174. return BigUint::new(ored);
  175. }
  176. }
  177. impl BitXor<BigUint, BigUint> for BigUint {
  178. fn bitxor(&self, other: &BigUint) -> BigUint {
  179. let zeros = ZERO_VEC.iter().cycle();
  180. let (a, b) = if self.data.len() > other.data.len() { (self, other) } else { (other, self) };
  181. let xored = a.data.iter().zip(b.data.iter().chain(zeros)).map(
  182. |(ai, bi)| *ai ^ *bi
  183. ).collect();
  184. return BigUint::new(xored);
  185. }
  186. }
  187. impl Shl<uint, BigUint> for BigUint {
  188. #[inline]
  189. fn shl(&self, rhs: &uint) -> BigUint {
  190. let n_unit = *rhs / BigDigit::BITS;
  191. let n_bits = *rhs % BigDigit::BITS;
  192. return self.shl_unit(n_unit).shl_bits(n_bits);
  193. }
  194. }
  195. impl Shr<uint, BigUint> for BigUint {
  196. #[inline]
  197. fn shr(&self, rhs: &uint) -> BigUint {
  198. let n_unit = *rhs / BigDigit::BITS;
  199. let n_bits = *rhs % BigDigit::BITS;
  200. return self.shr_unit(n_unit).shr_bits(n_bits);
  201. }
  202. }
  203. impl Zero for BigUint {
  204. #[inline]
  205. fn zero() -> BigUint { BigUint::new(Vec::new()) }
  206. #[inline]
  207. fn is_zero(&self) -> bool { self.data.is_empty() }
  208. }
  209. impl One for BigUint {
  210. #[inline]
  211. fn one() -> BigUint { BigUint::new(vec!(1)) }
  212. }
  213. impl Unsigned for BigUint {}
  214. impl Add<BigUint, BigUint> for BigUint {
  215. fn add(&self, other: &BigUint) -> BigUint {
  216. let zeros = ZERO_VEC.iter().cycle();
  217. let (a, b) = if self.data.len() > other.data.len() { (self, other) } else { (other, self) };
  218. let mut carry = 0;
  219. let mut sum: Vec<BigDigit> = a.data.iter().zip(b.data.iter().chain(zeros)).map(|(ai, bi)| {
  220. let (hi, lo) = BigDigit::from_doublebigdigit(
  221. (*ai as DoubleBigDigit) + (*bi as DoubleBigDigit) + (carry as DoubleBigDigit));
  222. carry = hi;
  223. lo
  224. }).collect();
  225. if carry != 0 { sum.push(carry); }
  226. return BigUint::new(sum);
  227. }
  228. }
  229. impl Sub<BigUint, BigUint> for BigUint {
  230. fn sub(&self, other: &BigUint) -> BigUint {
  231. let new_len = cmp::max(self.data.len(), other.data.len());
  232. let zeros = ZERO_VEC.iter().cycle();
  233. let (a, b) = (self.data.iter().chain(zeros.clone()), other.data.iter().chain(zeros));
  234. let mut borrow = 0i;
  235. let diff: Vec<BigDigit> = a.take(new_len).zip(b).map(|(ai, bi)| {
  236. let (hi, lo) = BigDigit::from_doublebigdigit(
  237. BigDigit::BASE
  238. + (*ai as DoubleBigDigit)
  239. - (*bi as DoubleBigDigit)
  240. - (borrow as DoubleBigDigit)
  241. );
  242. /*
  243. hi * (base) + lo == 1*(base) + ai - bi - borrow
  244. => ai - bi - borrow < 0 <=> hi == 0
  245. */
  246. borrow = if hi == 0 { 1 } else { 0 };
  247. lo
  248. }).collect();
  249. assert!(borrow == 0,
  250. "Cannot subtract other from self because other is larger than self.");
  251. return BigUint::new(diff);
  252. }
  253. }
  254. impl Mul<BigUint, BigUint> for BigUint {
  255. fn mul(&self, other: &BigUint) -> BigUint {
  256. if self.is_zero() || other.is_zero() { return Zero::zero(); }
  257. let (s_len, o_len) = (self.data.len(), other.data.len());
  258. if s_len == 1 { return mul_digit(other, self.data[0]); }
  259. if o_len == 1 { return mul_digit(self, other.data[0]); }
  260. // Using Karatsuba multiplication
  261. // (a1 * base + a0) * (b1 * base + b0)
  262. // = a1*b1 * base^2 +
  263. // (a1*b1 + a0*b0 - (a1-b0)*(b1-a0)) * base +
  264. // a0*b0
  265. let half_len = cmp::max(s_len, o_len) / 2;
  266. let (s_hi, s_lo) = cut_at(self, half_len);
  267. let (o_hi, o_lo) = cut_at(other, half_len);
  268. let ll = s_lo * o_lo;
  269. let hh = s_hi * o_hi;
  270. let mm = {
  271. let (s1, n1) = sub_sign(s_hi, s_lo);
  272. let (s2, n2) = sub_sign(o_hi, o_lo);
  273. match (s1, s2) {
  274. (Equal, _) | (_, Equal) => hh + ll,
  275. (Less, Greater) | (Greater, Less) => hh + ll + (n1 * n2),
  276. (Less, Less) | (Greater, Greater) => hh + ll - (n1 * n2)
  277. }
  278. };
  279. return ll + mm.shl_unit(half_len) + hh.shl_unit(half_len * 2);
  280. fn mul_digit(a: &BigUint, n: BigDigit) -> BigUint {
  281. if n == 0 { return Zero::zero(); }
  282. if n == 1 { return (*a).clone(); }
  283. let mut carry = 0;
  284. let mut prod: Vec<BigDigit> = a.data.iter().map(|ai| {
  285. let (hi, lo) = BigDigit::from_doublebigdigit(
  286. (*ai as DoubleBigDigit) * (n as DoubleBigDigit) + (carry as DoubleBigDigit)
  287. );
  288. carry = hi;
  289. lo
  290. }).collect();
  291. if carry != 0 { prod.push(carry); }
  292. return BigUint::new(prod);
  293. }
  294. #[inline]
  295. fn cut_at(a: &BigUint, n: uint) -> (BigUint, BigUint) {
  296. let mid = cmp::min(a.data.len(), n);
  297. (BigUint::from_slice(a.data[mid ..]),
  298. BigUint::from_slice(a.data[.. mid]))
  299. }
  300. #[inline]
  301. fn sub_sign(a: BigUint, b: BigUint) -> (Ordering, BigUint) {
  302. match a.cmp(&b) {
  303. Less => (Less, b - a),
  304. Greater => (Greater, a - b),
  305. _ => (Equal, Zero::zero())
  306. }
  307. }
  308. }
  309. }
  310. impl Div<BigUint, BigUint> for BigUint {
  311. #[inline]
  312. fn div(&self, other: &BigUint) -> BigUint {
  313. let (q, _) = self.div_rem(other);
  314. return q;
  315. }
  316. }
  317. impl Rem<BigUint, BigUint> for BigUint {
  318. #[inline]
  319. fn rem(&self, other: &BigUint) -> BigUint {
  320. let (_, r) = self.div_rem(other);
  321. return r;
  322. }
  323. }
  324. impl Neg<BigUint> for BigUint {
  325. #[inline]
  326. fn neg(&self) -> BigUint { panic!() }
  327. }
  328. impl CheckedAdd for BigUint {
  329. #[inline]
  330. fn checked_add(&self, v: &BigUint) -> Option<BigUint> {
  331. return Some(self.add(v));
  332. }
  333. }
  334. impl CheckedSub for BigUint {
  335. #[inline]
  336. fn checked_sub(&self, v: &BigUint) -> Option<BigUint> {
  337. if *self < *v {
  338. return None;
  339. }
  340. return Some(self.sub(v));
  341. }
  342. }
  343. impl CheckedMul for BigUint {
  344. #[inline]
  345. fn checked_mul(&self, v: &BigUint) -> Option<BigUint> {
  346. return Some(self.mul(v));
  347. }
  348. }
  349. impl CheckedDiv for BigUint {
  350. #[inline]
  351. fn checked_div(&self, v: &BigUint) -> Option<BigUint> {
  352. if v.is_zero() {
  353. return None;
  354. }
  355. return Some(self.div(v));
  356. }
  357. }
  358. impl Integer for BigUint {
  359. #[inline]
  360. fn div_rem(&self, other: &BigUint) -> (BigUint, BigUint) {
  361. self.div_mod_floor(other)
  362. }
  363. #[inline]
  364. fn div_floor(&self, other: &BigUint) -> BigUint {
  365. let (d, _) = self.div_mod_floor(other);
  366. return d;
  367. }
  368. #[inline]
  369. fn mod_floor(&self, other: &BigUint) -> BigUint {
  370. let (_, m) = self.div_mod_floor(other);
  371. return m;
  372. }
  373. fn div_mod_floor(&self, other: &BigUint) -> (BigUint, BigUint) {
  374. if other.is_zero() { panic!() }
  375. if self.is_zero() { return (Zero::zero(), Zero::zero()); }
  376. if *other == One::one() { return ((*self).clone(), Zero::zero()); }
  377. match self.cmp(other) {
  378. Less => return (Zero::zero(), (*self).clone()),
  379. Equal => return (One::one(), Zero::zero()),
  380. Greater => {} // Do nothing
  381. }
  382. let mut shift = 0;
  383. let mut n = *other.data.last().unwrap();
  384. while n < (1 << BigDigit::BITS - 2) {
  385. n <<= 1;
  386. shift += 1;
  387. }
  388. assert!(shift < BigDigit::BITS);
  389. let (d, m) = div_mod_floor_inner(*self << shift, *other << shift);
  390. return (d, m >> shift);
  391. fn div_mod_floor_inner(a: BigUint, b: BigUint) -> (BigUint, BigUint) {
  392. let mut m = a;
  393. let mut d: BigUint = Zero::zero();
  394. let mut n = 1;
  395. while m >= b {
  396. let (d0, d_unit, b_unit) = div_estimate(&m, &b, n);
  397. let mut d0 = d0;
  398. let mut prod = b * d0;
  399. while prod > m {
  400. // FIXME(#5992): assignment operator overloads
  401. // d0 -= d_unit
  402. d0 = d0 - d_unit;
  403. // FIXME(#5992): assignment operator overloads
  404. // prod -= b_unit;
  405. prod = prod - b_unit
  406. }
  407. if d0.is_zero() {
  408. n = 2;
  409. continue;
  410. }
  411. n = 1;
  412. // FIXME(#5992): assignment operator overloads
  413. // d += d0;
  414. d = d + d0;
  415. // FIXME(#5992): assignment operator overloads
  416. // m -= prod;
  417. m = m - prod;
  418. }
  419. return (d, m);
  420. }
  421. fn div_estimate(a: &BigUint, b: &BigUint, n: uint)
  422. -> (BigUint, BigUint, BigUint) {
  423. if a.data.len() < n {
  424. return (Zero::zero(), Zero::zero(), (*a).clone());
  425. }
  426. let an = a.data[a.data.len() - n ..];
  427. let bn = *b.data.last().unwrap();
  428. let mut d = Vec::with_capacity(an.len());
  429. let mut carry = 0;
  430. for elt in an.iter().rev() {
  431. let ai = BigDigit::to_doublebigdigit(carry, *elt);
  432. let di = ai / (bn as DoubleBigDigit);
  433. assert!(di < BigDigit::BASE);
  434. carry = (ai % (bn as DoubleBigDigit)) as BigDigit;
  435. d.push(di as BigDigit)
  436. }
  437. d.reverse();
  438. let shift = (a.data.len() - an.len()) - (b.data.len() - 1);
  439. if shift == 0 {
  440. return (BigUint::new(d), One::one(), (*b).clone());
  441. }
  442. let one: BigUint = One::one();
  443. return (BigUint::new(d).shl_unit(shift),
  444. one.shl_unit(shift),
  445. b.shl_unit(shift));
  446. }
  447. }
  448. /// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
  449. ///
  450. /// The result is always positive.
  451. #[inline]
  452. fn gcd(&self, other: &BigUint) -> BigUint {
  453. // Use Euclid's algorithm
  454. let mut m = (*self).clone();
  455. let mut n = (*other).clone();
  456. while !m.is_zero() {
  457. let temp = m;
  458. m = n % temp;
  459. n = temp;
  460. }
  461. return n;
  462. }
  463. /// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
  464. #[inline]
  465. fn lcm(&self, other: &BigUint) -> BigUint { ((*self * *other) / self.gcd(other)) }
  466. /// Deprecated, use `is_multiple_of` instead.
  467. #[deprecated = "function renamed to `is_multiple_of`"]
  468. #[inline]
  469. fn divides(&self, other: &BigUint) -> bool { return self.is_multiple_of(other); }
  470. /// Returns `true` if the number is a multiple of `other`.
  471. #[inline]
  472. fn is_multiple_of(&self, other: &BigUint) -> bool { (*self % *other).is_zero() }
  473. /// Returns `true` if the number is divisible by `2`.
  474. #[inline]
  475. fn is_even(&self) -> bool {
  476. // Considering only the last digit.
  477. match self.data.head() {
  478. Some(x) => x.is_even(),
  479. None => true
  480. }
  481. }
  482. /// Returns `true` if the number is not divisible by `2`.
  483. #[inline]
  484. fn is_odd(&self) -> bool { !self.is_even() }
  485. }
  486. impl ToPrimitive for BigUint {
  487. #[inline]
  488. fn to_i64(&self) -> Option<i64> {
  489. self.to_u64().and_then(|n| {
  490. // If top bit of u64 is set, it's too large to convert to i64.
  491. if n >> 63 == 0 {
  492. Some(n as i64)
  493. } else {
  494. None
  495. }
  496. })
  497. }
  498. // `DoubleBigDigit` size dependent
  499. #[inline]
  500. fn to_u64(&self) -> Option<u64> {
  501. match self.data.len() {
  502. 0 => Some(0),
  503. 1 => Some(self.data[0] as u64),
  504. 2 => Some(BigDigit::to_doublebigdigit(self.data[1], self.data[0])
  505. as u64),
  506. _ => None
  507. }
  508. }
  509. }
  510. impl FromPrimitive for BigUint {
  511. #[inline]
  512. fn from_i64(n: i64) -> Option<BigUint> {
  513. if n > 0 {
  514. FromPrimitive::from_u64(n as u64)
  515. } else if n == 0 {
  516. Some(Zero::zero())
  517. } else {
  518. None
  519. }
  520. }
  521. // `DoubleBigDigit` size dependent
  522. #[inline]
  523. fn from_u64(n: u64) -> Option<BigUint> {
  524. let n = match BigDigit::from_doublebigdigit(n) {
  525. (0, 0) => Zero::zero(),
  526. (0, n0) => BigUint::new(vec!(n0)),
  527. (n1, n0) => BigUint::new(vec!(n0, n1))
  528. };
  529. Some(n)
  530. }
  531. }
  532. /// A generic trait for converting a value to a `BigUint`.
  533. pub trait ToBigUint {
  534. /// Converts the value of `self` to a `BigUint`.
  535. fn to_biguint(&self) -> Option<BigUint>;
  536. }
  537. impl ToBigUint for BigInt {
  538. #[inline]
  539. fn to_biguint(&self) -> Option<BigUint> {
  540. if self.sign == Plus {
  541. Some(self.data.clone())
  542. } else if self.sign == NoSign {
  543. Some(Zero::zero())
  544. } else {
  545. None
  546. }
  547. }
  548. }
  549. impl ToBigUint for BigUint {
  550. #[inline]
  551. fn to_biguint(&self) -> Option<BigUint> {
  552. Some(self.clone())
  553. }
  554. }
  555. macro_rules! impl_to_biguint(
  556. ($T:ty, $from_ty:path) => {
  557. impl ToBigUint for $T {
  558. #[inline]
  559. fn to_biguint(&self) -> Option<BigUint> {
  560. $from_ty(*self)
  561. }
  562. }
  563. }
  564. )
  565. impl_to_biguint!(int, FromPrimitive::from_int)
  566. impl_to_biguint!(i8, FromPrimitive::from_i8)
  567. impl_to_biguint!(i16, FromPrimitive::from_i16)
  568. impl_to_biguint!(i32, FromPrimitive::from_i32)
  569. impl_to_biguint!(i64, FromPrimitive::from_i64)
  570. impl_to_biguint!(uint, FromPrimitive::from_uint)
  571. impl_to_biguint!(u8, FromPrimitive::from_u8)
  572. impl_to_biguint!(u16, FromPrimitive::from_u16)
  573. impl_to_biguint!(u32, FromPrimitive::from_u32)
  574. impl_to_biguint!(u64, FromPrimitive::from_u64)
  575. fn to_str_radix(me: &BigUint, radix: uint) -> String {
  576. assert!(1 < radix && radix <= 16, "The radix must be within (1, 16]");
  577. let (base, max_len) = get_radix_base(radix);
  578. if base == BigDigit::BASE {
  579. return fill_concat(me.data[], radix, max_len)
  580. }
  581. return fill_concat(convert_base(me, base)[], radix, max_len);
  582. fn convert_base(n: &BigUint, base: DoubleBigDigit) -> Vec<BigDigit> {
  583. let divider = base.to_biguint().unwrap();
  584. let mut result = Vec::new();
  585. let mut m = n.clone();
  586. while m >= divider {
  587. let (d, m0) = m.div_mod_floor(&divider);
  588. result.push(m0.to_uint().unwrap() as BigDigit);
  589. m = d;
  590. }
  591. if !m.is_zero() {
  592. result.push(m.to_uint().unwrap() as BigDigit);
  593. }
  594. return result;
  595. }
  596. fn fill_concat(v: &[BigDigit], radix: uint, l: uint) -> String {
  597. if v.is_empty() {
  598. return "0".to_string()
  599. }
  600. let mut s = String::with_capacity(v.len() * l);
  601. for n in v.iter().rev() {
  602. let ss = fmt::radix(*n as uint, radix as u8).to_string();
  603. s.push_str("0".repeat(l - ss.len())[]);
  604. s.push_str(ss[]);
  605. }
  606. s.trim_left_chars('0').to_string()
  607. }
  608. }
  609. fn to_str_radix_signed(me: &BigInt, radix: uint) -> String {
  610. match me.sign {
  611. Plus => to_str_radix(&me.data, radix),
  612. NoSign => "0".to_string(),
  613. Minus => format!("-{}", to_str_radix(&me.data, radix)),
  614. }
  615. }
  616. impl FromStrRadix for BigUint {
  617. /// Creates and initializes a `BigUint`.
  618. #[inline]
  619. fn from_str_radix(s: &str, radix: uint) -> Option<BigUint> {
  620. let (base, unit_len) = get_radix_base(radix);
  621. let base_num = match base.to_biguint() {
  622. Some(base_num) => base_num,
  623. None => { return None; }
  624. };
  625. let mut end = s.len();
  626. let mut n: BigUint = Zero::zero();
  627. let mut power: BigUint = One::one();
  628. loop {
  629. let start = cmp::max(end, unit_len) - unit_len;
  630. match FromStrRadix::from_str_radix(s[start .. end], radix) {
  631. Some(d) => {
  632. let d: Option<BigUint> = FromPrimitive::from_uint(d);
  633. match d {
  634. Some(d) => {
  635. // FIXME(#5992): assignment operator overloads
  636. // n += d * power;
  637. n = n + d * power;
  638. }
  639. None => { return None; }
  640. }
  641. }
  642. None => { return None; }
  643. }
  644. if end <= unit_len {
  645. return Some(n);
  646. }
  647. end -= unit_len;
  648. // FIXME(#5992): assignment operator overloads
  649. // power *= base_num;
  650. power = power * base_num;
  651. }
  652. }
  653. }
  654. impl BigUint {
  655. /// Creates and initializes a `BigUint`.
  656. ///
  657. /// The digits are be in base 2^32.
  658. #[inline]
  659. pub fn new(mut digits: Vec<BigDigit>) -> BigUint {
  660. // omit trailing zeros
  661. let new_len = digits.iter().rposition(|n| *n != 0).map_or(0, |p| p + 1);
  662. digits.truncate(new_len);
  663. BigUint { data: digits }
  664. }
  665. /// Creates and initializes a `BigUint`.
  666. ///
  667. /// The digits are be in base 2^32.
  668. #[inline]
  669. pub fn from_slice(slice: &[BigDigit]) -> BigUint {
  670. BigUint::new(slice.to_vec())
  671. }
  672. /// Creates and initializes a `BigUint`.
  673. #[inline]
  674. pub fn parse_bytes(buf: &[u8], radix: uint) -> Option<BigUint> {
  675. str::from_utf8(buf).and_then(|s| FromStrRadix::from_str_radix(s, radix))
  676. }
  677. #[inline]
  678. fn shl_unit(&self, n_unit: uint) -> BigUint {
  679. if n_unit == 0 || self.is_zero() { return (*self).clone(); }
  680. let mut v = Vec::from_elem(n_unit, ZERO_BIG_DIGIT);
  681. v.push_all(self.data[]);
  682. BigUint::new(v)
  683. }
  684. #[inline]
  685. fn shl_bits(&self, n_bits: uint) -> BigUint {
  686. if n_bits == 0 || self.is_zero() { return (*self).clone(); }
  687. let mut carry = 0;
  688. let mut shifted: Vec<BigDigit> = self.data.iter().map(|elem| {
  689. let (hi, lo) = BigDigit::from_doublebigdigit(
  690. (*elem as DoubleBigDigit) << n_bits | (carry as DoubleBigDigit)
  691. );
  692. carry = hi;
  693. lo
  694. }).collect();
  695. if carry != 0 { shifted.push(carry); }
  696. return BigUint::new(shifted);
  697. }
  698. #[inline]
  699. fn shr_unit(&self, n_unit: uint) -> BigUint {
  700. if n_unit == 0 { return (*self).clone(); }
  701. if self.data.len() < n_unit { return Zero::zero(); }
  702. BigUint::from_slice(self.data[n_unit ..])
  703. }
  704. #[inline]
  705. fn shr_bits(&self, n_bits: uint) -> BigUint {
  706. if n_bits == 0 || self.data.is_empty() { return (*self).clone(); }
  707. let mut borrow = 0;
  708. let mut shifted_rev = Vec::with_capacity(self.data.len());
  709. for elem in self.data.iter().rev() {
  710. shifted_rev.push((*elem >> n_bits) | borrow);
  711. borrow = *elem << (BigDigit::BITS - n_bits);
  712. }
  713. let shifted = { shifted_rev.reverse(); shifted_rev };
  714. return BigUint::new(shifted);
  715. }
  716. /// Determines the fewest bits necessary to express the `BigUint`.
  717. pub fn bits(&self) -> uint {
  718. if self.is_zero() { return 0; }
  719. let zeros = self.data.last().unwrap().leading_zeros();
  720. return self.data.len()*BigDigit::BITS - zeros;
  721. }
  722. }
  723. // `DoubleBigDigit` size dependent
  724. #[inline]
  725. fn get_radix_base(radix: uint) -> (DoubleBigDigit, uint) {
  726. match radix {
  727. 2 => (4294967296, 32),
  728. 3 => (3486784401, 20),
  729. 4 => (4294967296, 16),
  730. 5 => (1220703125, 13),
  731. 6 => (2176782336, 12),
  732. 7 => (1977326743, 11),
  733. 8 => (1073741824, 10),
  734. 9 => (3486784401, 10),
  735. 10 => (1000000000, 9),
  736. 11 => (2357947691, 9),
  737. 12 => (429981696, 8),
  738. 13 => (815730721, 8),
  739. 14 => (1475789056, 8),
  740. 15 => (2562890625, 8),
  741. 16 => (4294967296, 8),
  742. _ => panic!("The radix must be within (1, 16]")
  743. }
  744. }
  745. /// A Sign is a `BigInt`'s composing element.
  746. #[deriving(PartialEq, PartialOrd, Eq, Ord, Clone, Show)]
  747. pub enum Sign { Minus, NoSign, Plus }
  748. impl Neg<Sign> for Sign {
  749. /// Negate Sign value.
  750. #[inline]
  751. fn neg(&self) -> Sign {
  752. match *self {
  753. Minus => Plus,
  754. NoSign => NoSign,
  755. Plus => Minus
  756. }
  757. }
  758. }
  759. /// A big signed integer type.
  760. #[deriving(Clone)]
  761. pub struct BigInt {
  762. sign: Sign,
  763. data: BigUint
  764. }
  765. impl PartialEq for BigInt {
  766. #[inline]
  767. fn eq(&self, other: &BigInt) -> bool {
  768. self.cmp(other) == Equal
  769. }
  770. }
  771. impl Eq for BigInt {}
  772. impl PartialOrd for BigInt {
  773. #[inline]
  774. fn partial_cmp(&self, other: &BigInt) -> Option<Ordering> {
  775. Some(self.cmp(other))
  776. }
  777. }
  778. impl Ord for BigInt {
  779. #[inline]
  780. fn cmp(&self, other: &BigInt) -> Ordering {
  781. let scmp = self.sign.cmp(&other.sign);
  782. if scmp != Equal { return scmp; }
  783. match self.sign {
  784. NoSign => Equal,
  785. Plus => self.data.cmp(&other.data),
  786. Minus => other.data.cmp(&self.data),
  787. }
  788. }
  789. }
  790. impl Default for BigInt {
  791. #[inline]
  792. fn default() -> BigInt { Zero::zero() }
  793. }
  794. impl fmt::Show for BigInt {
  795. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  796. write!(f, "{}", to_str_radix_signed(self, 10))
  797. }
  798. }
  799. impl<S: hash::Writer> hash::Hash<S> for BigInt {
  800. fn hash(&self, state: &mut S) {
  801. (self.sign == Plus).hash(state);
  802. self.data.hash(state);
  803. }
  804. }
  805. impl FromStr for BigInt {
  806. #[inline]
  807. fn from_str(s: &str) -> Option<BigInt> {
  808. FromStrRadix::from_str_radix(s, 10)
  809. }
  810. }
  811. impl Num for BigInt {}
  812. impl Shl<uint, BigInt> for BigInt {
  813. #[inline]
  814. fn shl(&self, rhs: &uint) -> BigInt {
  815. BigInt::from_biguint(self.sign, self.data << *rhs)
  816. }
  817. }
  818. impl Shr<uint, BigInt> for BigInt {
  819. #[inline]
  820. fn shr(&self, rhs: &uint) -> BigInt {
  821. BigInt::from_biguint(self.sign, self.data >> *rhs)
  822. }
  823. }
  824. impl Zero for BigInt {
  825. #[inline]
  826. fn zero() -> BigInt {
  827. BigInt::from_biguint(NoSign, Zero::zero())
  828. }
  829. #[inline]
  830. fn is_zero(&self) -> bool { self.sign == NoSign }
  831. }
  832. impl One for BigInt {
  833. #[inline]
  834. fn one() -> BigInt {
  835. BigInt::from_biguint(Plus, One::one())
  836. }
  837. }
  838. impl Signed for BigInt {
  839. #[inline]
  840. fn abs(&self) -> BigInt {
  841. match self.sign {
  842. Plus | NoSign => self.clone(),
  843. Minus => BigInt::from_biguint(Plus, self.data.clone())
  844. }
  845. }
  846. #[inline]
  847. fn abs_sub(&self, other: &BigInt) -> BigInt {
  848. if *self <= *other { Zero::zero() } else { *self - *other }
  849. }
  850. #[inline]
  851. fn signum(&self) -> BigInt {
  852. match self.sign {
  853. Plus => BigInt::from_biguint(Plus, One::one()),
  854. Minus => BigInt::from_biguint(Minus, One::one()),
  855. NoSign => Zero::zero(),
  856. }
  857. }
  858. #[inline]
  859. fn is_positive(&self) -> bool { self.sign == Plus }
  860. #[inline]
  861. fn is_negative(&self) -> bool { self.sign == Minus }
  862. }
  863. impl Add<BigInt, BigInt> for BigInt {
  864. #[inline]
  865. fn add(&self, other: &BigInt) -> BigInt {
  866. match (self.sign, other.sign) {
  867. (NoSign, _) => other.clone(),
  868. (_, NoSign) => self.clone(),
  869. (Plus, Plus) => BigInt::from_biguint(Plus, self.data + other.data),
  870. (Plus, Minus) => *self - (-*other),
  871. (Minus, Plus) => *other - (-*self),
  872. (Minus, Minus) => -((-*self) + (-*other))
  873. }
  874. }
  875. }
  876. impl Sub<BigInt, BigInt> for BigInt {
  877. #[inline]
  878. fn sub(&self, other: &BigInt) -> BigInt {
  879. match (self.sign, other.sign) {
  880. (NoSign, _) => -*other,
  881. (_, NoSign) => self.clone(),
  882. (Plus, Plus) => match self.data.cmp(&other.data) {
  883. Less => BigInt::from_biguint(Minus, other.data - self.data),
  884. Greater => BigInt::from_biguint(Plus, self.data - other.data),
  885. Equal => Zero::zero()
  886. },
  887. (Plus, Minus) => *self + (-*other),
  888. (Minus, Plus) => -((-*self) + *other),
  889. (Minus, Minus) => (-*other) - (-*self)
  890. }
  891. }
  892. }
  893. impl Mul<BigInt, BigInt> for BigInt {
  894. #[inline]
  895. fn mul(&self, other: &BigInt) -> BigInt {
  896. match (self.sign, other.sign) {
  897. (NoSign, _) | (_, NoSign) => Zero::zero(),
  898. (Plus, Plus) | (Minus, Minus) => {
  899. BigInt::from_biguint(Plus, self.data * other.data)
  900. },
  901. (Plus, Minus) | (Minus, Plus) => {
  902. BigInt::from_biguint(Minus, self.data * other.data)
  903. }
  904. }
  905. }
  906. }
  907. impl Div<BigInt, BigInt> for BigInt {
  908. #[inline]
  909. fn div(&self, other: &BigInt) -> BigInt {
  910. let (q, _) = self.div_rem(other);
  911. q
  912. }
  913. }
  914. impl Rem<BigInt, BigInt> for BigInt {
  915. #[inline]
  916. fn rem(&self, other: &BigInt) -> BigInt {
  917. let (_, r) = self.div_rem(other);
  918. r
  919. }
  920. }
  921. impl Neg<BigInt> for BigInt {
  922. #[inline]
  923. fn neg(&self) -> BigInt {
  924. BigInt::from_biguint(self.sign.neg(), self.data.clone())
  925. }
  926. }
  927. impl CheckedAdd for BigInt {
  928. #[inline]
  929. fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
  930. return Some(self.add(v));
  931. }
  932. }
  933. impl CheckedSub for BigInt {
  934. #[inline]
  935. fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
  936. return Some(self.sub(v));
  937. }
  938. }
  939. impl CheckedMul for BigInt {
  940. #[inline]
  941. fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
  942. return Some(self.mul(v));
  943. }
  944. }
  945. impl CheckedDiv for BigInt {
  946. #[inline]
  947. fn checked_div(&self, v: &BigInt) -> Option<BigInt> {
  948. if v.is_zero() {
  949. return None;
  950. }
  951. return Some(self.div(v));
  952. }
  953. }
  954. impl Integer for BigInt {
  955. #[inline]
  956. fn div_rem(&self, other: &BigInt) -> (BigInt, BigInt) {
  957. // r.sign == self.sign
  958. let (d_ui, r_ui) = self.data.div_mod_floor(&other.data);
  959. let d = BigInt::from_biguint(Plus, d_ui);
  960. let r = BigInt::from_biguint(Plus, r_ui);
  961. match (self.sign, other.sign) {
  962. (_, NoSign) => panic!(),
  963. (Plus, Plus) | (NoSign, Plus) => ( d, r),
  964. (Plus, Minus) | (NoSign, Minus) => (-d, r),
  965. (Minus, Plus) => (-d, -r),
  966. (Minus, Minus) => ( d, -r)
  967. }
  968. }
  969. #[inline]
  970. fn div_floor(&self, other: &BigInt) -> BigInt {
  971. let (d, _) = self.div_mod_floor(other);
  972. d
  973. }
  974. #[inline]
  975. fn mod_floor(&self, other: &BigInt) -> BigInt {
  976. let (_, m) = self.div_mod_floor(other);
  977. m
  978. }
  979. fn div_mod_floor(&self, other: &BigInt) -> (BigInt, BigInt) {
  980. // m.sign == other.sign
  981. let (d_ui, m_ui) = self.data.div_rem(&other.data);
  982. let d = BigInt::from_biguint(Plus, d_ui);
  983. let m = BigInt::from_biguint(Plus, m_ui);
  984. match (self.sign, other.sign) {
  985. (_, NoSign) => panic!(),
  986. (Plus, Plus) | (NoSign, Plus) => (d, m),
  987. (Plus, Minus) | (NoSign, Minus) => if m.is_zero() {
  988. (-d, Zero::zero())
  989. } else {
  990. (-d - One::one(), m + *other)
  991. },
  992. (Minus, Plus) => if m.is_zero() {
  993. (-d, Zero::zero())
  994. } else {
  995. (-d - One::one(), *other - m)
  996. },
  997. (Minus, Minus) => (d, -m)
  998. }
  999. }
  1000. /// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
  1001. ///
  1002. /// The result is always positive.
  1003. #[inline]
  1004. fn gcd(&self, other: &BigInt) -> BigInt {
  1005. BigInt::from_biguint(Plus, self.data.gcd(&other.data))
  1006. }
  1007. /// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
  1008. #[inline]
  1009. fn lcm(&self, other: &BigInt) -> BigInt {
  1010. BigInt::from_biguint(Plus, self.data.lcm(&other.data))
  1011. }
  1012. /// Deprecated, use `is_multiple_of` instead.
  1013. #[deprecated = "function renamed to `is_multiple_of`"]
  1014. #[inline]
  1015. fn divides(&self, other: &BigInt) -> bool { return self.is_multiple_of(other); }
  1016. /// Returns `true` if the number is a multiple of `other`.
  1017. #[inline]
  1018. fn is_multiple_of(&self, other: &BigInt) -> bool { self.data.is_multiple_of(&other.data) }
  1019. /// Returns `true` if the number is divisible by `2`.
  1020. #[inline]
  1021. fn is_even(&self) -> bool { self.data.is_even() }
  1022. /// Returns `true` if the number is not divisible by `2`.
  1023. #[inline]
  1024. fn is_odd(&self) -> bool { self.data.is_odd() }
  1025. }
  1026. impl ToPrimitive for BigInt {
  1027. #[inline]
  1028. fn to_i64(&self) -> Option<i64> {
  1029. match self.sign {
  1030. Plus => self.data.to_i64(),
  1031. NoSign => Some(0),
  1032. Minus => {
  1033. self.data.to_u64().and_then(|n| {
  1034. let m: u64 = 1 << 63;
  1035. if n < m {
  1036. Some(-(n as i64))
  1037. } else if n == m {
  1038. Some(i64::MIN)
  1039. } else {
  1040. None
  1041. }
  1042. })
  1043. }
  1044. }
  1045. }
  1046. #[inline]
  1047. fn to_u64(&self) -> Option<u64> {
  1048. match self.sign {
  1049. Plus => self.data.to_u64(),
  1050. NoSign => Some(0),
  1051. Minus => None
  1052. }
  1053. }
  1054. }
  1055. impl FromPrimitive for BigInt {
  1056. #[inline]
  1057. fn from_i64(n: i64) -> Option<BigInt> {
  1058. if n > 0 {
  1059. FromPrimitive::from_u64(n as u64).and_then(|n| {
  1060. Some(BigInt::from_biguint(Plus, n))
  1061. })
  1062. } else if n < 0 {
  1063. FromPrimitive::from_u64(u64::MAX - (n as u64) + 1).and_then(
  1064. |n| {
  1065. Some(BigInt::from_biguint(Minus, n))
  1066. })
  1067. } else {
  1068. Some(Zero::zero())
  1069. }
  1070. }
  1071. #[inline]
  1072. fn from_u64(n: u64) -> Option<BigInt> {
  1073. if n == 0 {
  1074. Some(Zero::zero())
  1075. } else {
  1076. FromPrimitive::from_u64(n).and_then(|n| {
  1077. Some(BigInt::from_biguint(Plus, n))
  1078. })
  1079. }
  1080. }
  1081. }
  1082. /// A generic trait for converting a value to a `BigInt`.
  1083. pub trait ToBigInt {
  1084. /// Converts the value of `self` to a `BigInt`.
  1085. fn to_bigint(&self) -> Option<BigInt>;
  1086. }
  1087. impl ToBigInt for BigInt {
  1088. #[inline]
  1089. fn to_bigint(&self) -> Option<BigInt> {
  1090. Some(self.clone())
  1091. }
  1092. }
  1093. impl ToBigInt for BigUint {
  1094. #[inline]
  1095. fn to_bigint(&self) -> Option<BigInt> {
  1096. if self.is_zero() {
  1097. Some(Zero::zero())
  1098. } else {
  1099. Some(BigInt { sign: Plus, data: self.clone() })
  1100. }
  1101. }
  1102. }
  1103. macro_rules! impl_to_bigint(
  1104. ($T:ty, $from_ty:path) => {
  1105. impl ToBigInt for $T {
  1106. #[inline]
  1107. fn to_bigint(&self) -> Option<BigInt> {
  1108. $from_ty(*self)
  1109. }
  1110. }
  1111. }
  1112. )
  1113. impl_to_bigint!(int, FromPrimitive::from_int)
  1114. impl_to_bigint!(i8, FromPrimitive::from_i8)
  1115. impl_to_bigint!(i16, FromPrimitive::from_i16)
  1116. impl_to_bigint!(i32, FromPrimitive::from_i32)
  1117. impl_to_bigint!(i64, FromPrimitive::from_i64)
  1118. impl_to_bigint!(uint, FromPrimitive::from_uint)
  1119. impl_to_bigint!(u8, FromPrimitive::from_u8)
  1120. impl_to_bigint!(u16, FromPrimitive::from_u16)
  1121. impl_to_bigint!(u32, FromPrimitive::from_u32)
  1122. impl_to_bigint!(u64, FromPrimitive::from_u64)
  1123. impl FromStrRadix for BigInt {
  1124. /// Creates and initializes a BigInt.
  1125. #[inline]
  1126. fn from_str_radix(s: &str, radix: uint) -> Option<BigInt> {
  1127. if s.is_empty() { return None; }
  1128. let mut sign = Plus;
  1129. let mut start = 0;
  1130. if s.starts_with("-") {
  1131. sign = Minus;
  1132. start = 1;
  1133. }
  1134. FromStrRadix::from_str_radix(s[start ..], radix)
  1135. .map(|bu| BigInt::from_biguint(sign, bu))
  1136. }
  1137. }
  1138. pub trait RandBigInt {
  1139. /// Generate a random `BigUint` of the given bit size.
  1140. fn gen_biguint(&mut self, bit_size: uint) -> BigUint;
  1141. /// Generate a random BigInt of the given bit size.
  1142. fn gen_bigint(&mut self, bit_size: uint) -> BigInt;
  1143. /// Generate a random `BigUint` less than the given bound. Fails
  1144. /// when the bound is zero.
  1145. fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint;
  1146. /// Generate a random `BigUint` within the given range. The lower
  1147. /// bound is inclusive; the upper bound is exclusive. Fails when
  1148. /// the upper bound is not greater than the lower bound.
  1149. fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint;
  1150. /// Generate a random `BigInt` within the given range. The lower
  1151. /// bound is inclusive; the upper bound is exclusive. Fails when
  1152. /// the upper bound is not greater than the lower bound.
  1153. fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt;
  1154. }
  1155. impl<R: Rng> RandBigInt for R {
  1156. fn gen_biguint(&mut self, bit_size: uint) -> BigUint {
  1157. let (digits, rem) = bit_size.div_rem(&BigDigit::BITS);
  1158. let mut data = Vec::with_capacity(digits+1);
  1159. for _ in range(0, digits) {
  1160. data.push(self.gen());
  1161. }
  1162. if rem > 0 {
  1163. let final_digit: BigDigit = self.gen();
  1164. data.push(final_digit >> (BigDigit::BITS - rem));
  1165. }
  1166. BigUint::new(data)
  1167. }
  1168. fn gen_bigint(&mut self, bit_size: uint) -> BigInt {
  1169. // Generate a random BigUint...
  1170. let biguint = self.gen_biguint(bit_size);
  1171. // ...and then randomly assign it a Sign...
  1172. let sign = if biguint.is_zero() {
  1173. // ...except that if the BigUint is zero, we need to try
  1174. // again with probability 0.5. This is because otherwise,
  1175. // the probability of generating a zero BigInt would be
  1176. // double that of any other number.
  1177. if self.gen() {
  1178. return self.gen_bigint(bit_size);
  1179. } else {
  1180. NoSign
  1181. }
  1182. } else if self.gen() {
  1183. Plus
  1184. } else {
  1185. Minus
  1186. };
  1187. BigInt::from_biguint(sign, biguint)
  1188. }
  1189. fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint {
  1190. assert!(!bound.is_zero());
  1191. let bits = bound.bits();
  1192. loop {
  1193. let n = self.gen_biguint(bits);
  1194. if n < *bound { return n; }
  1195. }
  1196. }
  1197. fn gen_biguint_range(&mut self,
  1198. lbound: &BigUint,
  1199. ubound: &BigUint)
  1200. -> BigUint {
  1201. assert!(*lbound < *ubound);
  1202. return *lbound + self.gen_biguint_below(&(*ubound - *lbound));
  1203. }
  1204. fn gen_bigint_range(&mut self,
  1205. lbound: &BigInt,
  1206. ubound: &BigInt)
  1207. -> BigInt {
  1208. assert!(*lbound < *ubound);
  1209. let delta = (*ubound - *lbound).to_biguint().unwrap();
  1210. return *lbound + self.gen_biguint_below(&delta).to_bigint().unwrap();
  1211. }
  1212. }
  1213. impl BigInt {
  1214. /// Creates and initializes a BigInt.
  1215. ///
  1216. /// The digits are be in base 2^32.
  1217. #[inline]
  1218. pub fn new(sign: Sign, digits: Vec<BigDigit>) -> BigInt {
  1219. BigInt::from_biguint(sign, BigUint::new(digits))
  1220. }
  1221. /// Creates and initializes a `BigInt`.
  1222. ///
  1223. /// The digits are be in base 2^32.
  1224. #[inline]
  1225. pub fn from_biguint(sign: Sign, data: BigUint) -> BigInt {
  1226. if sign == NoSign || data.is_zero() {
  1227. return BigInt { sign: NoSign, data: Zero::zero() };
  1228. }
  1229. BigInt { sign: sign, data: data }
  1230. }
  1231. /// Creates and initializes a `BigInt`.
  1232. #[inline]
  1233. pub fn from_slice(sign: Sign, slice: &[BigDigit]) -> BigInt {
  1234. BigInt::from_biguint(sign, BigUint::from_slice(slice))
  1235. }
  1236. /// Creates and initializes a `BigInt`.
  1237. #[inline]
  1238. pub fn parse_bytes(buf: &[u8], radix: uint) -> Option<BigInt> {
  1239. str::from_utf8(buf).and_then(|s| FromStrRadix::from_str_radix(s, radix))
  1240. }
  1241. /// Converts this `BigInt` into a `BigUint`, if it's not negative.
  1242. #[inline]
  1243. pub fn to_biguint(&self) -> Option<BigUint> {
  1244. match self.sign {
  1245. Plus => Some(self.data.clone()),
  1246. NoSign => Some(Zero::zero()),
  1247. Minus => None
  1248. }
  1249. }
  1250. }
  1251. #[cfg(test)]
  1252. mod biguint_tests {
  1253. use Integer;
  1254. use super::{BigDigit, BigUint, ToBigUint, to_str_radix};
  1255. use super::{Plus, BigInt, RandBigInt, ToBigInt};
  1256. use std::cmp::{Less, Equal, Greater};
  1257. use std::from_str::FromStr;
  1258. use std::i64;
  1259. use std::num::{Zero, One, FromStrRadix};
  1260. use std::num::{ToPrimitive, FromPrimitive};
  1261. use std::num::CheckedDiv;
  1262. use std::rand::task_rng;
  1263. use std::u64;
  1264. use std::hash::hash;
  1265. #[test]
  1266. fn test_from_slice() {
  1267. fn check(slice: &[BigDigit], data: &[BigDigit]) {
  1268. assert!(data == BigUint::from_slice(slice).data.as_slice());
  1269. }
  1270. check([1], [1]);
  1271. check([0, 0, 0], []);
  1272. check([1, 2, 0, 0], [1, 2]);
  1273. check([0, 0, 1, 2], [0, 0, 1, 2]);
  1274. check([0, 0, 1, 2, 0, 0], [0, 0, 1, 2]);
  1275. check([-1], [-1]);
  1276. }
  1277. #[test]
  1278. fn test_cmp() {
  1279. let data: [&[_], ..7] = [ &[], &[1], &[2], &[-1], &[0, 1], &[2, 1], &[1, 1, 1] ];
  1280. let data: Vec<BigUint> = data.iter().map(|v| BigUint::from_slice(*v)).collect();
  1281. for (i, ni) in data.iter().enumerate() {
  1282. for (j0, nj) in data.slice(i, data.len()).iter().enumerate() {
  1283. let j = j0 + i;
  1284. if i == j {
  1285. assert_eq!(ni.cmp(nj), Equal);
  1286. assert_eq!(nj.cmp(ni), Equal);
  1287. assert_eq!(ni, nj);
  1288. assert!(!(ni != nj));
  1289. assert!(ni <= nj);
  1290. assert!(ni >= nj);
  1291. assert!(!(ni < nj));
  1292. assert!(!(ni > nj));
  1293. } else {
  1294. assert_eq!(ni.cmp(nj), Less);
  1295. assert_eq!(nj.cmp(ni), Greater);
  1296. assert!(!(ni == nj));
  1297. assert!(ni != nj);
  1298. assert!(ni <= nj);
  1299. assert!(!(ni >= nj));
  1300. assert!(ni < nj);
  1301. assert!(!(ni > nj));
  1302. assert!(!(nj <= ni));
  1303. assert!(nj >= ni);
  1304. assert!(!(nj < ni));
  1305. assert!(nj > ni);
  1306. }
  1307. }
  1308. }
  1309. }
  1310. #[test]
  1311. fn test_hash() {
  1312. let a = BigUint::new(vec!());
  1313. let b = BigUint::new(vec!(0));
  1314. let c = BigUint::new(vec!(1));
  1315. let d = BigUint::new(vec!(1,0,0,0,0,0));
  1316. let e = BigUint::new(vec!(0,0,0,0,0,1));
  1317. assert!(hash(&a) == hash(&b));
  1318. assert!(hash(&b) != hash(&c));
  1319. assert!(hash(&c) == hash(&d));
  1320. assert!(hash(&d) != hash(&e));
  1321. }
  1322. #[test]
  1323. fn test_bitand() {
  1324. fn check(left: &[BigDigit],
  1325. right: &[BigDigit],
  1326. expected: &[BigDigit]) {
  1327. assert_eq!(BigUint::from_slice(left) & BigUint::from_slice(right),
  1328. BigUint::from_slice(expected));
  1329. }
  1330. check([], [], []);
  1331. check([268, 482, 17],
  1332. [964, 54],
  1333. [260, 34]);
  1334. }
  1335. #[test]
  1336. fn test_bitor() {
  1337. fn check(left: &[BigDigit],
  1338. right: &[BigDigit],
  1339. expected: &[BigDigit]) {
  1340. assert_eq!(BigUint::from_slice(left) | BigUint::from_slice(right),
  1341. BigUint::from_slice(expected));
  1342. }
  1343. check([], [], []);
  1344. check([268, 482, 17],
  1345. [964, 54],
  1346. [972, 502, 17]);
  1347. }
  1348. #[test]
  1349. fn test_bitxor() {
  1350. fn check(left: &[BigDigit],
  1351. right: &[BigDigit],
  1352. expected: &[BigDigit]) {
  1353. assert_eq!(BigUint::from_slice(left) ^ BigUint::from_slice(right),
  1354. BigUint::from_slice(expected));
  1355. }
  1356. check([], [], []);
  1357. check([268, 482, 17],
  1358. [964, 54],
  1359. [712, 468, 17]);
  1360. }
  1361. #[test]
  1362. fn test_shl() {
  1363. fn check(s: &str, shift: uint, ans: &str) {
  1364. let opt_biguint: Option<BigUint> = FromStrRadix::from_str_radix(s, 16);
  1365. let bu = to_str_radix(&(opt_biguint.unwrap() << shift), 16);
  1366. assert_eq!(bu.as_slice(), ans);
  1367. }
  1368. check("0", 3, "0");
  1369. check("1", 3, "8");
  1370. check("1\
  1371. 0000\
  1372. 0000\
  1373. 0000\
  1374. 0001\
  1375. 0000\
  1376. 0000\
  1377. 0000\
  1378. 0001",
  1379. 3,
  1380. "8\
  1381. 0000\
  1382. 0000\
  1383. 0000\
  1384. 0008\
  1385. 0000\
  1386. 0000\
  1387. 0000\
  1388. 0008");
  1389. check("1\
  1390. 0000\
  1391. 0001\
  1392. 0000\
  1393. 0001",
  1394. 2,
  1395. "4\
  1396. 0000\
  1397. 0004\
  1398. 0000\
  1399. 0004");
  1400. check("1\
  1401. 0001\
  1402. 0001",
  1403. 1,
  1404. "2\
  1405. 0002\
  1406. 0002");
  1407. check("\
  1408. 4000\
  1409. 0000\
  1410. 0000\
  1411. 0000",
  1412. 3,
  1413. "2\
  1414. 0000\
  1415. 0000\
  1416. 0000\
  1417. 0000");
  1418. check("4000\
  1419. 0000",
  1420. 2,
  1421. "1\
  1422. 0000\
  1423. 0000");
  1424. check("4000",
  1425. 2,
  1426. "1\
  1427. 0000");
  1428. check("4000\
  1429. 0000\
  1430. 0000\
  1431. 0000",
  1432. 67,
  1433. "2\
  1434. 0000\
  1435. 0000\
  1436. 0000\
  1437. 0000\
  1438. 0000\
  1439. 0000\
  1440. 0000\
  1441. 0000");
  1442. check("4000\
  1443. 0000",
  1444. 35,
  1445. "2\
  1446. 0000\
  1447. 0000\
  1448. 0000\
  1449. 0000");
  1450. check("4000",
  1451. 19,
  1452. "2\
  1453. 0000\
  1454. 0000");
  1455. check("fedc\
  1456. ba98\
  1457. 7654\
  1458. 3210\
  1459. fedc\
  1460. ba98\
  1461. 7654\
  1462. 3210",
  1463. 4,
  1464. "f\
  1465. edcb\
  1466. a987\
  1467. 6543\
  1468. 210f\
  1469. edcb\
  1470. a987\
  1471. 6543\
  1472. 2100");
  1473. check("88887777666655554444333322221111", 16,
  1474. "888877776666555544443333222211110000");
  1475. }
  1476. #[test]
  1477. fn test_shr() {
  1478. fn check(s: &str, shift: uint, ans: &str) {
  1479. let opt_biguint: Option<BigUint> =
  1480. FromStrRadix::from_str_radix(s, 16);
  1481. let bu = to_str_radix(&(opt_biguint.unwrap() >> shift), 16);
  1482. assert_eq!(bu.as_slice(), ans);
  1483. }
  1484. check("0", 3, "0");
  1485. check("f", 3, "1");
  1486. check("1\
  1487. 0000\
  1488. 0000\
  1489. 0000\
  1490. 0001\
  1491. 0000\
  1492. 0000\
  1493. 0000\
  1494. 0001",
  1495. 3,
  1496. "2000\
  1497. 0000\
  1498. 0000\
  1499. 0000\
  1500. 2000\
  1501. 0000\
  1502. 0000\
  1503. 0000");
  1504. check("1\
  1505. 0000\
  1506. 0001\
  1507. 0000\
  1508. 0001",
  1509. 2,
  1510. "4000\
  1511. 0000\
  1512. 4000\
  1513. 0000");
  1514. check("1\
  1515. 0001\
  1516. 0001",
  1517. 1,
  1518. "8000\
  1519. 8000");
  1520. check("2\
  1521. 0000\
  1522. 0000\
  1523. 0000\
  1524. 0001\
  1525. 0000\
  1526. 0000\
  1527. 0000\
  1528. 0001",
  1529. 67,
  1530. "4000\
  1531. 0000\
  1532. 0000\
  1533. 0000");
  1534. check("2\
  1535. 0000\
  1536. 0001\
  1537. 0000\
  1538. 0001",
  1539. 35,
  1540. "4000\
  1541. 0000");
  1542. check("2\
  1543. 0001\
  1544. 0001",
  1545. 19,
  1546. "4000");
  1547. check("1\
  1548. 0000\
  1549. 0000\
  1550. 0000\
  1551. 0000",
  1552. 1,
  1553. "8000\
  1554. 0000\
  1555. 0000\
  1556. 0000");
  1557. check("1\
  1558. 0000\
  1559. 0000",
  1560. 1,
  1561. "8000\
  1562. 0000");
  1563. check("1\
  1564. 0000",
  1565. 1,
  1566. "8000");
  1567. check("f\
  1568. edcb\
  1569. a987\
  1570. 6543\
  1571. 210f\
  1572. edcb\
  1573. a987\
  1574. 6543\
  1575. 2100",
  1576. 4,
  1577. "fedc\
  1578. ba98\
  1579. 7654\
  1580. 3210\
  1581. fedc\
  1582. ba98\
  1583. 7654\
  1584. 3210");
  1585. check("888877776666555544443333222211110000", 16,
  1586. "88887777666655554444333322221111");
  1587. }
  1588. // `DoubleBigDigit` size dependent
  1589. #[test]
  1590. fn test_convert_i64() {
  1591. fn check(b1: BigUint, i: i64) {
  1592. let b2: BigUint = FromPrimitive::from_i64(i).unwrap();
  1593. assert!(b1 == b2);
  1594. assert!(b1.to_i64().unwrap() == i);
  1595. }
  1596. check(Zero::zero(), 0);
  1597. check(One::one(), 1);
  1598. check(i64::MAX.to_biguint().unwrap(), i64::MAX);
  1599. check(BigUint::new(vec!( )), 0);
  1600. check(BigUint::new(vec!( 1 )), (1 << (0*BigDigit::BITS)));
  1601. check(BigUint::new(vec!(-1 )), (1 << (1*BigDigit::BITS)) - 1);
  1602. check(BigUint::new(vec!( 0, 1 )), (1 << (1*BigDigit::BITS)));
  1603. check(BigUint::new(vec!(-1, -1 >> 1)), i64::MAX);
  1604. assert_eq!(i64::MIN.to_biguint(), None);
  1605. assert_eq!(BigUint::new(vec!(-1, -1 )).to_i64(), None);
  1606. assert_eq!(BigUint::new(vec!( 0, 0, 1)).to_i64(), None);
  1607. assert_eq!(BigUint::new(vec!(-1, -1, -1)).to_i64(), None);
  1608. }
  1609. // `DoubleBigDigit` size dependent
  1610. #[test]
  1611. fn test_convert_u64() {
  1612. fn check(b1: BigUint, u: u64) {
  1613. let b2: BigUint = FromPrimitive::from_u64(u).unwrap();
  1614. assert!(b1 == b2);
  1615. assert!(b1.to_u64().unwrap() == u);
  1616. }
  1617. check(Zero::zero(), 0);
  1618. check(One::one(), 1);
  1619. check(u64::MIN.to_biguint().unwrap(), u64::MIN);
  1620. check(u64::MAX.to_biguint().unwrap(), u64::MAX);
  1621. check(BigUint::new(vec!( )), 0);
  1622. check(BigUint::new(vec!( 1 )), (1 << (0*BigDigit::BITS)));
  1623. check(BigUint::new(vec!(-1 )), (1 << (1*BigDigit::BITS)) - 1);
  1624. check(BigUint::new(vec!( 0, 1)), (1 << (1*BigDigit::BITS)));
  1625. check(BigUint::new(vec!(-1, -1)), u64::MAX);
  1626. assert_eq!(BigUint::new(vec!( 0, 0, 1)).to_u64(), None);
  1627. assert_eq!(BigUint::new(vec!(-1, -1, -1)).to_u64(), None);
  1628. }
  1629. #[test]
  1630. fn test_convert_to_bigint() {
  1631. fn check(n: BigUint, ans: BigInt) {
  1632. assert_eq!(n.to_bigint().unwrap(), ans);
  1633. assert_eq!(n.to_bigint().unwrap().to_biguint().unwrap(), n);
  1634. }
  1635. check(Zero::zero(), Zero::zero());
  1636. check(BigUint::new(vec!(1,2,3)),
  1637. BigInt::from_biguint(Plus, BigUint::new(vec!(1,2,3))));
  1638. }
  1639. const SUM_TRIPLES: &'static [(&'static [BigDigit],
  1640. &'static [BigDigit],
  1641. &'static [BigDigit])] = &[
  1642. (&[], &[], &[]),
  1643. (&[], &[ 1], &[ 1]),
  1644. (&[ 1], &[ 1], &[ 2]),
  1645. (&[ 1], &[ 1, 1], &[ 2, 1]),
  1646. (&[ 1], &[-1], &[ 0, 1]),
  1647. (&[ 1], &[-1, -1], &[ 0, 0, 1]),
  1648. (&[-1, -1], &[-1, -1], &[-2, -1, 1]),
  1649. (&[ 1, 1, 1], &[-1, -1], &[ 0, 1, 2]),
  1650. (&[ 2, 2, 1], &[-1, -2], &[ 1, 1, 2])
  1651. ];
  1652. #[test]
  1653. fn test_add() {
  1654. for elm in SUM_TRIPLES.iter() {
  1655. let (a_vec, b_vec, c_vec) = *elm;
  1656. let a = BigUint::from_slice(a_vec);
  1657. let b = BigUint::from_slice(b_vec);
  1658. let c = BigUint::from_slice(c_vec);
  1659. assert!(a + b == c);
  1660. assert!(b + a == c);
  1661. }
  1662. }
  1663. #[test]
  1664. fn test_sub() {
  1665. for elm in SUM_TRIPLES.iter() {
  1666. let (a_vec, b_vec, c_vec) = *elm;
  1667. let a = BigUint::from_slice(a_vec);
  1668. let b = BigUint::from_slice(b_vec);
  1669. let c = BigUint::from_slice(c_vec);
  1670. assert!(c - a == b);
  1671. assert!(c - b == a);
  1672. }
  1673. }
  1674. #[test]
  1675. #[should_fail]
  1676. fn test_sub_fail_on_underflow() {
  1677. let (a, b) : (BigUint, BigUint) = (Zero::zero(), One::one());
  1678. a - b;
  1679. }
  1680. const MUL_TRIPLES: &'static [(&'static [BigDigit],
  1681. &'static [BigDigit],
  1682. &'static [BigDigit])] = &[
  1683. (&[], &[], &[]),
  1684. (&[], &[ 1], &[]),
  1685. (&[ 2], &[], &[]),
  1686. (&[ 1], &[ 1], &[1]),
  1687. (&[ 2], &[ 3], &[ 6]),
  1688. (&[ 1], &[ 1, 1, 1], &[1, 1, 1]),
  1689. (&[ 1, 2, 3], &[ 3], &[ 3, 6, 9]),
  1690. (&[ 1, 1, 1], &[-1], &[-1, -1, -1]),
  1691. (&[ 1, 2, 3], &[-1], &[-1, -2, -2, 2]),
  1692. (&[ 1, 2, 3, 4], &[-1], &[-1, -2, -2, -2, 3]),
  1693. (&[-1], &[-1], &[ 1, -2]),
  1694. (&[-1, -1], &[-1], &[ 1, -1, -2]),
  1695. (&[-1, -1, -1], &[-1], &[ 1, -1, -1, -2]),
  1696. (&[-1, -1, -1, -1], &[-1], &[ 1, -1, -1, -1, -2]),
  1697. (&[-1/2 + 1], &[ 2], &[ 0, 1]),
  1698. (&[0, -1/2 + 1], &[ 2], &[ 0, 0, 1]),
  1699. (&[ 1, 2], &[ 1, 2, 3], &[1, 4, 7, 6]),
  1700. (&[-1, -1], &[-1, -1, -1], &[1, 0, -1, -2, -1]),
  1701. (&[-1, -1, -1], &[-1, -1, -1, -1], &[1, 0, 0, -1, -2, -1, -1]),
  1702. (&[ 0, 0, 1], &[ 1, 2, 3], &[0, 0, 1, 2, 3]),
  1703. (&[ 0, 0, 1], &[ 0, 0, 0, 1], &[0, 0, 0, 0, 0, 1])
  1704. ];
  1705. const DIV_REM_QUADRUPLES: &'static [(&'static [BigDigit],
  1706. &'static [BigDigit],
  1707. &'static [BigDigit],
  1708. &'static [BigDigit])]
  1709. = &[
  1710. (&[ 1], &[ 2], &[], &[1]),
  1711. (&[ 1, 1], &[ 2], &[-1/2+1], &[1]),
  1712. (&[ 1, 1, 1], &[ 2], &[-1/2+1, -1/2+1], &[1]),
  1713. (&[ 0, 1], &[-1], &[1], &[1]),
  1714. (&[-1, -1], &[-2], &[2, 1], &[3])
  1715. ];
  1716. #[test]
  1717. fn test_mul() {
  1718. for elm in MUL_TRIPLES.iter() {
  1719. let (a_vec, b_vec, c_vec) = *elm;
  1720. let a = BigUint::from_slice(a_vec);
  1721. let b = BigUint::from_slice(b_vec);
  1722. let c = BigUint::from_slice(c_vec);
  1723. assert!(a * b == c);
  1724. assert!(b * a == c);
  1725. }
  1726. for elm in DIV_REM_QUADRUPLES.iter() {
  1727. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  1728. let a = BigUint::from_slice(a_vec);
  1729. let b = BigUint::from_slice(b_vec);
  1730. let c = BigUint::from_slice(c_vec);
  1731. let d = BigUint::from_slice(d_vec);
  1732. assert!(a == b * c + d);
  1733. assert!(a == c * b + d);
  1734. }
  1735. }
  1736. #[test]
  1737. fn test_div_rem() {
  1738. for elm in MUL_TRIPLES.iter() {
  1739. let (a_vec, b_vec, c_vec) = *elm;
  1740. let a = BigUint::from_slice(a_vec);
  1741. let b = BigUint::from_slice(b_vec);
  1742. let c = BigUint::from_slice(c_vec);
  1743. if !a.is_zero() {
  1744. assert_eq!(c.div_rem(&a), (b.clone(), Zero::zero()));
  1745. }
  1746. if !b.is_zero() {
  1747. assert_eq!(c.div_rem(&b), (a.clone(), Zero::zero()));
  1748. }
  1749. }
  1750. for elm in DIV_REM_QUADRUPLES.iter() {
  1751. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  1752. let a = BigUint::from_slice(a_vec);
  1753. let b = BigUint::from_slice(b_vec);
  1754. let c = BigUint::from_slice(c_vec);
  1755. let d = BigUint::from_slice(d_vec);
  1756. if !b.is_zero() { assert!(a.div_rem(&b) == (c, d)); }
  1757. }
  1758. }
  1759. #[test]
  1760. fn test_checked_add() {
  1761. for elm in SUM_TRIPLES.iter() {
  1762. let (a_vec, b_vec, c_vec) = *elm;
  1763. let a = BigUint::from_slice(a_vec);
  1764. let b = BigUint::from_slice(b_vec);
  1765. let c = BigUint::from_slice(c_vec);
  1766. assert!(a.checked_add(&b).unwrap() == c);
  1767. assert!(b.checked_add(&a).unwrap() == c);
  1768. }
  1769. }
  1770. #[test]
  1771. fn test_checked_sub() {
  1772. for elm in SUM_TRIPLES.iter() {
  1773. let (a_vec, b_vec, c_vec) = *elm;
  1774. let a = BigUint::from_slice(a_vec);
  1775. let b = BigUint::from_slice(b_vec);
  1776. let c = BigUint::from_slice(c_vec);
  1777. assert!(c.checked_sub(&a).unwrap() == b);
  1778. assert!(c.checked_sub(&b).unwrap() == a);
  1779. if a > c {
  1780. assert!(a.checked_sub(&c).is_none());
  1781. }
  1782. if b > c {
  1783. assert!(b.checked_sub(&c).is_none());
  1784. }
  1785. }
  1786. }
  1787. #[test]
  1788. fn test_checked_mul() {
  1789. for elm in MUL_TRIPLES.iter() {
  1790. let (a_vec, b_vec, c_vec) = *elm;
  1791. let a = BigUint::from_slice(a_vec);
  1792. let b = BigUint::from_slice(b_vec);
  1793. let c = BigUint::from_slice(c_vec);
  1794. assert!(a.checked_mul(&b).unwrap() == c);
  1795. assert!(b.checked_mul(&a).unwrap() == c);
  1796. }
  1797. for elm in DIV_REM_QUADRUPLES.iter() {
  1798. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  1799. let a = BigUint::from_slice(a_vec);
  1800. let b = BigUint::from_slice(b_vec);
  1801. let c = BigUint::from_slice(c_vec);
  1802. let d = BigUint::from_slice(d_vec);
  1803. assert!(a == b.checked_mul(&c).unwrap() + d);
  1804. assert!(a == c.checked_mul(&b).unwrap() + d);
  1805. }
  1806. }
  1807. #[test]
  1808. fn test_checked_div() {
  1809. for elm in MUL_TRIPLES.iter() {
  1810. let (a_vec, b_vec, c_vec) = *elm;
  1811. let a = BigUint::from_slice(a_vec);
  1812. let b = BigUint::from_slice(b_vec);
  1813. let c = BigUint::from_slice(c_vec);
  1814. if !a.is_zero() {
  1815. assert!(c.checked_div(&a).unwrap() == b);
  1816. }
  1817. if !b.is_zero() {
  1818. assert!(c.checked_div(&b).unwrap() == a);
  1819. }
  1820. assert!(c.checked_div(&Zero::zero()).is_none());
  1821. }
  1822. }
  1823. #[test]
  1824. fn test_gcd() {
  1825. fn check(a: uint, b: uint, c: uint) {
  1826. let big_a: BigUint = FromPrimitive::from_uint(a).unwrap();
  1827. let big_b: BigUint = FromPrimitive::from_uint(b).unwrap();
  1828. let big_c: BigUint = FromPrimitive::from_uint(c).unwrap();
  1829. assert_eq!(big_a.gcd(&big_b), big_c);
  1830. }
  1831. check(10, 2, 2);
  1832. check(10, 3, 1);
  1833. check(0, 3, 3);
  1834. check(3, 3, 3);
  1835. check(56, 42, 14);
  1836. }
  1837. #[test]
  1838. fn test_lcm() {
  1839. fn check(a: uint, b: uint, c: uint) {
  1840. let big_a: BigUint = FromPrimitive::from_uint(a).unwrap();
  1841. let big_b: BigUint = FromPrimitive::from_uint(b).unwrap();
  1842. let big_c: BigUint = FromPrimitive::from_uint(c).unwrap();
  1843. assert_eq!(big_a.lcm(&big_b), big_c);
  1844. }
  1845. check(1, 0, 0);
  1846. check(0, 1, 0);
  1847. check(1, 1, 1);
  1848. check(8, 9, 72);
  1849. check(11, 5, 55);
  1850. check(99, 17, 1683);
  1851. }
  1852. #[test]
  1853. fn test_is_even() {
  1854. let one: BigUint = FromStr::from_str("1").unwrap();
  1855. let two: BigUint = FromStr::from_str("2").unwrap();
  1856. let thousand: BigUint = FromStr::from_str("1000").unwrap();
  1857. let big: BigUint = FromStr::from_str("1000000000000000000000").unwrap();
  1858. let bigger: BigUint = FromStr::from_str("1000000000000000000001").unwrap();
  1859. assert!(one.is_odd());
  1860. assert!(two.is_even());
  1861. assert!(thousand.is_even());
  1862. assert!(big.is_even());
  1863. assert!(bigger.is_odd());
  1864. assert!((one << 64).is_even());
  1865. assert!(((one << 64) + one).is_odd());
  1866. }
  1867. fn to_str_pairs() -> Vec<(BigUint, Vec<(uint, String)>)> {
  1868. let bits = BigDigit::BITS;
  1869. vec!(( Zero::zero(), vec!(
  1870. (2, "0".to_string()), (3, "0".to_string())
  1871. )), ( BigUint::from_slice([ 0xff ]), vec!(
  1872. (2, "11111111".to_string()),
  1873. (3, "100110".to_string()),
  1874. (4, "3333".to_string()),
  1875. (5, "2010".to_string()),
  1876. (6, "1103".to_string()),
  1877. (7, "513".to_string()),
  1878. (8, "377".to_string()),
  1879. (9, "313".to_string()),
  1880. (10, "255".to_string()),
  1881. (11, "212".to_string()),
  1882. (12, "193".to_string()),
  1883. (13, "168".to_string()),
  1884. (14, "143".to_string()),
  1885. (15, "120".to_string()),
  1886. (16, "ff".to_string())
  1887. )), ( BigUint::from_slice([ 0xfff ]), vec!(
  1888. (2, "111111111111".to_string()),
  1889. (4, "333333".to_string()),
  1890. (16, "fff".to_string())
  1891. )), ( BigUint::from_slice([ 1, 2 ]), vec!(
  1892. (2,
  1893. format!("10{}1", "0".repeat(bits - 1))),
  1894. (4,
  1895. format!("2{}1", "0".repeat(bits / 2 - 1))),
  1896. (10, match bits {
  1897. 32 => "8589934593".to_string(),
  1898. 16 => "131073".to_string(),
  1899. _ => panic!()
  1900. }),
  1901. (16,
  1902. format!("2{}1", "0".repeat(bits / 4 - 1)))
  1903. )), ( BigUint::from_slice([ 1, 2, 3 ]), vec!(
  1904. (2,
  1905. format!("11{}10{}1",
  1906. "0".repeat(bits - 2),
  1907. "0".repeat(bits - 1))),
  1908. (4,
  1909. format!("3{}2{}1",
  1910. "0".repeat(bits / 2 - 1),
  1911. "0".repeat(bits / 2 - 1))),
  1912. (10, match bits {
  1913. 32 => "55340232229718589441".to_string(),
  1914. 16 => "12885032961".to_string(),
  1915. _ => panic!()
  1916. }),
  1917. (16,
  1918. format!("3{}2{}1",
  1919. "0".repeat(bits / 4 - 1),
  1920. "0".repeat(bits / 4 - 1)))
  1921. )) )
  1922. }
  1923. #[test]
  1924. fn test_to_str_radix() {
  1925. let r = to_str_pairs();
  1926. for num_pair in r.iter() {
  1927. let &(ref n, ref rs) = num_pair;
  1928. for str_pair in rs.iter() {
  1929. let &(ref radix, ref str) = str_pair;
  1930. assert_eq!(to_str_radix(n, *radix).as_slice(),
  1931. str.as_slice());
  1932. }
  1933. }
  1934. }
  1935. #[test]
  1936. fn test_from_str_radix() {
  1937. let r = to_str_pairs();
  1938. for num_pair in r.iter() {
  1939. let &(ref n, ref rs) = num_pair;
  1940. for str_pair in rs.iter() {
  1941. let &(ref radix, ref str) = str_pair;
  1942. assert_eq!(n,
  1943. &FromStrRadix::from_str_radix(str.as_slice(),
  1944. *radix).unwrap());
  1945. }
  1946. }
  1947. let zed: Option<BigUint> = FromStrRadix::from_str_radix("Z", 10);
  1948. assert_eq!(zed, None);
  1949. let blank: Option<BigUint> = FromStrRadix::from_str_radix("_", 2);
  1950. assert_eq!(blank, None);
  1951. let minus_one: Option<BigUint> = FromStrRadix::from_str_radix("-1",
  1952. 10);
  1953. assert_eq!(minus_one, None);
  1954. }
  1955. #[test]
  1956. fn test_factor() {
  1957. fn factor(n: uint) -> BigUint {
  1958. let mut f: BigUint = One::one();
  1959. for i in range(2, n + 1) {
  1960. // FIXME(#5992): assignment operator overloads
  1961. // f *= FromPrimitive::from_uint(i);
  1962. f = f * FromPrimitive::from_uint(i).unwrap();
  1963. }
  1964. return f;
  1965. }
  1966. fn check(n: uint, s: &str) {
  1967. let n = factor(n);
  1968. let ans = match FromStrRadix::from_str_radix(s, 10) {
  1969. Some(x) => x, None => panic!()
  1970. };
  1971. assert_eq!(n, ans);
  1972. }
  1973. check(3, "6");
  1974. check(10, "3628800");
  1975. check(20, "2432902008176640000");
  1976. check(30, "265252859812191058636308480000000");
  1977. }
  1978. #[test]
  1979. fn test_bits() {
  1980. assert_eq!(BigUint::new(vec!(0,0,0,0)).bits(), 0);
  1981. let n: BigUint = FromPrimitive::from_uint(0).unwrap();
  1982. assert_eq!(n.bits(), 0);
  1983. let n: BigUint = FromPrimitive::from_uint(1).unwrap();
  1984. assert_eq!(n.bits(), 1);
  1985. let n: BigUint = FromPrimitive::from_uint(3).unwrap();
  1986. assert_eq!(n.bits(), 2);
  1987. let n: BigUint = FromStrRadix::from_str_radix("4000000000", 16).unwrap();
  1988. assert_eq!(n.bits(), 39);
  1989. let one: BigUint = One::one();
  1990. assert_eq!((one << 426).bits(), 427);
  1991. }
  1992. #[test]
  1993. fn test_rand() {
  1994. let mut rng = task_rng();
  1995. let _n: BigUint = rng.gen_biguint(137);
  1996. assert!(rng.gen_biguint(0).is_zero());
  1997. }
  1998. #[test]
  1999. fn test_rand_range() {
  2000. let mut rng = task_rng();
  2001. for _ in range(0u, 10) {
  2002. assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_uint(236).unwrap(),
  2003. &FromPrimitive::from_uint(237).unwrap()),
  2004. FromPrimitive::from_uint(236).unwrap());
  2005. }
  2006. let l = FromPrimitive::from_uint(403469000 + 2352).unwrap();
  2007. let u = FromPrimitive::from_uint(403469000 + 3513).unwrap();
  2008. for _ in range(0u, 1000) {
  2009. let n: BigUint = rng.gen_biguint_below(&u);
  2010. assert!(n < u);
  2011. let n: BigUint = rng.gen_biguint_range(&l, &u);
  2012. assert!(n >= l);
  2013. assert!(n < u);
  2014. }
  2015. }
  2016. #[test]
  2017. #[should_fail]
  2018. fn test_zero_rand_range() {
  2019. task_rng().gen_biguint_range(&FromPrimitive::from_uint(54).unwrap(),
  2020. &FromPrimitive::from_uint(54).unwrap());
  2021. }
  2022. #[test]
  2023. #[should_fail]
  2024. fn test_negative_rand_range() {
  2025. let mut rng = task_rng();
  2026. let l = FromPrimitive::from_uint(2352).unwrap();
  2027. let u = FromPrimitive::from_uint(3513).unwrap();
  2028. // Switching u and l should fail:
  2029. let _n: BigUint = rng.gen_biguint_range(&u, &l);
  2030. }
  2031. }
  2032. #[cfg(test)]
  2033. mod bigint_tests {
  2034. use Integer;
  2035. use super::{BigDigit, BigUint, ToBigUint};
  2036. use super::{Sign, Minus, NoSign, Plus, BigInt, RandBigInt, ToBigInt};
  2037. use std::cmp::{Less, Equal, Greater};
  2038. use std::i64;
  2039. use std::num::CheckedDiv;
  2040. use std::num::{Zero, One, FromStrRadix};
  2041. use std::num::{ToPrimitive, FromPrimitive};
  2042. use std::rand::task_rng;
  2043. use std::u64;
  2044. use std::hash::hash;
  2045. #[test]
  2046. fn test_from_biguint() {
  2047. fn check(inp_s: Sign, inp_n: uint, ans_s: Sign, ans_n: uint) {
  2048. let inp = BigInt::from_biguint(inp_s, FromPrimitive::from_uint(inp_n).unwrap());
  2049. let ans = BigInt { sign: ans_s, data: FromPrimitive::from_uint(ans_n).unwrap()};
  2050. assert_eq!(inp, ans);
  2051. }
  2052. check(Plus, 1, Plus, 1);
  2053. check(Plus, 0, NoSign, 0);
  2054. check(Minus, 1, Minus, 1);
  2055. check(NoSign, 1, NoSign, 0);
  2056. }
  2057. #[test]
  2058. fn test_cmp() {
  2059. let vs: [&[BigDigit], ..4] = [ &[2 as BigDigit], &[1, 1], &[2, 1], &[1, 1, 1] ];
  2060. let mut nums = Vec::new();
  2061. for s in vs.iter().rev() {
  2062. nums.push(BigInt::from_slice(Minus, *s));
  2063. }
  2064. nums.push(Zero::zero());
  2065. nums.extend(vs.iter().map(|s| BigInt::from_slice(Plus, *s)));
  2066. for (i, ni) in nums.iter().enumerate() {
  2067. for (j0, nj) in nums.slice(i, nums.len()).iter().enumerate() {
  2068. let j = i + j0;
  2069. if i == j {
  2070. assert_eq!(ni.cmp(nj), Equal);
  2071. assert_eq!(nj.cmp(ni), Equal);
  2072. assert_eq!(ni, nj);
  2073. assert!(!(ni != nj));
  2074. assert!(ni <= nj);
  2075. assert!(ni >= nj);
  2076. assert!(!(ni < nj));
  2077. assert!(!(ni > nj));
  2078. } else {
  2079. assert_eq!(ni.cmp(nj), Less);
  2080. assert_eq!(nj.cmp(ni), Greater);
  2081. assert!(!(ni == nj));
  2082. assert!(ni != nj);
  2083. assert!(ni <= nj);
  2084. assert!(!(ni >= nj));
  2085. assert!(ni < nj);
  2086. assert!(!(ni > nj));
  2087. assert!(!(nj <= ni));
  2088. assert!(nj >= ni);
  2089. assert!(!(nj < ni));
  2090. assert!(nj > ni);
  2091. }
  2092. }
  2093. }
  2094. }
  2095. #[test]
  2096. fn test_hash() {
  2097. let a = BigInt::new(NoSign, vec!());
  2098. let b = BigInt::new(NoSign, vec!(0));
  2099. let c = BigInt::new(Plus, vec!(1));
  2100. let d = BigInt::new(Plus, vec!(1,0,0,0,0,0));
  2101. let e = BigInt::new(Plus, vec!(0,0,0,0,0,1));
  2102. let f = BigInt::new(Minus, vec!(1));
  2103. assert!(hash(&a) == hash(&b));
  2104. assert!(hash(&b) != hash(&c));
  2105. assert!(hash(&c) == hash(&d));
  2106. assert!(hash(&d) != hash(&e));
  2107. assert!(hash(&c) != hash(&f));
  2108. }
  2109. #[test]
  2110. fn test_convert_i64() {
  2111. fn check(b1: BigInt, i: i64) {
  2112. let b2: BigInt = FromPrimitive::from_i64(i).unwrap();
  2113. assert!(b1 == b2);
  2114. assert!(b1.to_i64().unwrap() == i);
  2115. }
  2116. check(Zero::zero(), 0);
  2117. check(One::one(), 1);
  2118. check(i64::MIN.to_bigint().unwrap(), i64::MIN);
  2119. check(i64::MAX.to_bigint().unwrap(), i64::MAX);
  2120. assert_eq!(
  2121. (i64::MAX as u64 + 1).to_bigint().unwrap().to_i64(),
  2122. None);
  2123. assert_eq!(
  2124. BigInt::from_biguint(Plus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_i64(),
  2125. None);
  2126. assert_eq!(
  2127. BigInt::from_biguint(Minus, BigUint::new(vec!(1,0,0,1<<(BigDigit::BITS-1)))).to_i64(),
  2128. None);
  2129. assert_eq!(
  2130. BigInt::from_biguint(Minus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_i64(),
  2131. None);
  2132. }
  2133. #[test]
  2134. fn test_convert_u64() {
  2135. fn check(b1: BigInt, u: u64) {
  2136. let b2: BigInt = FromPrimitive::from_u64(u).unwrap();
  2137. assert!(b1 == b2);
  2138. assert!(b1.to_u64().unwrap() == u);
  2139. }
  2140. check(Zero::zero(), 0);
  2141. check(One::one(), 1);
  2142. check(u64::MIN.to_bigint().unwrap(), u64::MIN);
  2143. check(u64::MAX.to_bigint().unwrap(), u64::MAX);
  2144. assert_eq!(
  2145. BigInt::from_biguint(Plus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_u64(),
  2146. None);
  2147. let max_value: BigUint = FromPrimitive::from_u64(u64::MAX).unwrap();
  2148. assert_eq!(BigInt::from_biguint(Minus, max_value).to_u64(), None);
  2149. assert_eq!(BigInt::from_biguint(Minus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_u64(), None);
  2150. }
  2151. #[test]
  2152. fn test_convert_to_biguint() {
  2153. fn check(n: BigInt, ans_1: BigUint) {
  2154. assert_eq!(n.to_biguint().unwrap(), ans_1);
  2155. assert_eq!(n.to_biguint().unwrap().to_bigint().unwrap(), n);
  2156. }
  2157. let zero: BigInt = Zero::zero();
  2158. let unsigned_zero: BigUint = Zero::zero();
  2159. let positive = BigInt::from_biguint(
  2160. Plus, BigUint::new(vec!(1,2,3)));
  2161. let negative = -positive;
  2162. check(zero, unsigned_zero);
  2163. check(positive, BigUint::new(vec!(1,2,3)));
  2164. assert_eq!(negative.to_biguint(), None);
  2165. }
  2166. const SUM_TRIPLES: &'static [(&'static [BigDigit],
  2167. &'static [BigDigit],
  2168. &'static [BigDigit])] = &[
  2169. (&[], &[], &[]),
  2170. (&[], &[ 1], &[ 1]),
  2171. (&[ 1], &[ 1], &[ 2]),
  2172. (&[ 1], &[ 1, 1], &[ 2, 1]),
  2173. (&[ 1], &[-1], &[ 0, 1]),
  2174. (&[ 1], &[-1, -1], &[ 0, 0, 1]),
  2175. (&[-1, -1], &[-1, -1], &[-2, -1, 1]),
  2176. (&[ 1, 1, 1], &[-1, -1], &[ 0, 1, 2]),
  2177. (&[ 2, 2, 1], &[-1, -2], &[ 1, 1, 2])
  2178. ];
  2179. #[test]
  2180. fn test_add() {
  2181. for elm in SUM_TRIPLES.iter() {
  2182. let (a_vec, b_vec, c_vec) = *elm;
  2183. let a = BigInt::from_slice(Plus, a_vec);
  2184. let b = BigInt::from_slice(Plus, b_vec);
  2185. let c = BigInt::from_slice(Plus, c_vec);
  2186. assert!(a + b == c);
  2187. assert!(b + a == c);
  2188. assert!(c + (-a) == b);
  2189. assert!(c + (-b) == a);
  2190. assert!(a + (-c) == (-b));
  2191. assert!(b + (-c) == (-a));
  2192. assert!((-a) + (-b) == (-c))
  2193. assert!(a + (-a) == Zero::zero());
  2194. }
  2195. }
  2196. #[test]
  2197. fn test_sub() {
  2198. for elm in SUM_TRIPLES.iter() {
  2199. let (a_vec, b_vec, c_vec) = *elm;
  2200. let a = BigInt::from_slice(Plus, a_vec);
  2201. let b = BigInt::from_slice(Plus, b_vec);
  2202. let c = BigInt::from_slice(Plus, c_vec);
  2203. assert!(c - a == b);
  2204. assert!(c - b == a);
  2205. assert!((-b) - a == (-c))
  2206. assert!((-a) - b == (-c))
  2207. assert!(b - (-a) == c);
  2208. assert!(a - (-b) == c);
  2209. assert!((-c) - (-a) == (-b));
  2210. assert!(a - a == Zero::zero());
  2211. }
  2212. }
  2213. static MUL_TRIPLES: &'static [(&'static [BigDigit],
  2214. &'static [BigDigit],
  2215. &'static [BigDigit])] = &[
  2216. (&[], &[], &[]),
  2217. (&[], &[ 1], &[]),
  2218. (&[ 2], &[], &[]),
  2219. (&[ 1], &[ 1], &[1]),
  2220. (&[ 2], &[ 3], &[ 6]),
  2221. (&[ 1], &[ 1, 1, 1], &[1, 1, 1]),
  2222. (&[ 1, 2, 3], &[ 3], &[ 3, 6, 9]),
  2223. (&[ 1, 1, 1], &[-1], &[-1, -1, -1]),
  2224. (&[ 1, 2, 3], &[-1], &[-1, -2, -2, 2]),
  2225. (&[ 1, 2, 3, 4], &[-1], &[-1, -2, -2, -2, 3]),
  2226. (&[-1], &[-1], &[ 1, -2]),
  2227. (&[-1, -1], &[-1], &[ 1, -1, -2]),
  2228. (&[-1, -1, -1], &[-1], &[ 1, -1, -1, -2]),
  2229. (&[-1, -1, -1, -1], &[-1], &[ 1, -1, -1, -1, -2]),
  2230. (&[-1/2 + 1], &[ 2], &[ 0, 1]),
  2231. (&[0, -1/2 + 1], &[ 2], &[ 0, 0, 1]),
  2232. (&[ 1, 2], &[ 1, 2, 3], &[1, 4, 7, 6]),
  2233. (&[-1, -1], &[-1, -1, -1], &[1, 0, -1, -2, -1]),
  2234. (&[-1, -1, -1], &[-1, -1, -1, -1], &[1, 0, 0, -1, -2, -1, -1]),
  2235. (&[ 0, 0, 1], &[ 1, 2, 3], &[0, 0, 1, 2, 3]),
  2236. (&[ 0, 0, 1], &[ 0, 0, 0, 1], &[0, 0, 0, 0, 0, 1])
  2237. ];
  2238. static DIV_REM_QUADRUPLES: &'static [(&'static [BigDigit],
  2239. &'static [BigDigit],
  2240. &'static [BigDigit],
  2241. &'static [BigDigit])]
  2242. = &[
  2243. (&[ 1], &[ 2], &[], &[1]),
  2244. (&[ 1, 1], &[ 2], &[-1/2+1], &[1]),
  2245. (&[ 1, 1, 1], &[ 2], &[-1/2+1, -1/2+1], &[1]),
  2246. (&[ 0, 1], &[-1], &[1], &[1]),
  2247. (&[-1, -1], &[-2], &[2, 1], &[3])
  2248. ];
  2249. #[test]
  2250. fn test_mul() {
  2251. for elm in MUL_TRIPLES.iter() {
  2252. let (a_vec, b_vec, c_vec) = *elm;
  2253. let a = BigInt::from_slice(Plus, a_vec);
  2254. let b = BigInt::from_slice(Plus, b_vec);
  2255. let c = BigInt::from_slice(Plus, c_vec);
  2256. assert!(a * b == c);
  2257. assert!(b * a == c);
  2258. assert!((-a) * b == -c);
  2259. assert!((-b) * a == -c);
  2260. }
  2261. for elm in DIV_REM_QUADRUPLES.iter() {
  2262. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  2263. let a = BigInt::from_slice(Plus, a_vec);
  2264. let b = BigInt::from_slice(Plus, b_vec);
  2265. let c = BigInt::from_slice(Plus, c_vec);
  2266. let d = BigInt::from_slice(Plus, d_vec);
  2267. assert!(a == b * c + d);
  2268. assert!(a == c * b + d);
  2269. }
  2270. }
  2271. #[test]
  2272. fn test_div_mod_floor() {
  2273. fn check_sub(a: &BigInt, b: &BigInt, ans_d: &BigInt, ans_m: &BigInt) {
  2274. let (d, m) = a.div_mod_floor(b);
  2275. if !m.is_zero() {
  2276. assert_eq!(m.sign, b.sign);
  2277. }
  2278. assert!(m.abs() <= b.abs());
  2279. assert!(*a == (*b) * d + m);
  2280. assert!(d == *ans_d);
  2281. assert!(m == *ans_m);
  2282. }
  2283. fn check(a: &BigInt, b: &BigInt, d: &BigInt, m: &BigInt) {
  2284. if m.is_zero() {
  2285. check_sub(a, b, d, m);
  2286. check_sub(a, &b.neg(), &d.neg(), m);
  2287. check_sub(&a.neg(), b, &d.neg(), m);
  2288. check_sub(&a.neg(), &b.neg(), d, m);
  2289. } else {
  2290. check_sub(a, b, d, m);
  2291. check_sub(a, &b.neg(), &(d.neg() - One::one()), &(*m - *b));
  2292. check_sub(&a.neg(), b, &(d.neg() - One::one()), &(*b - *m));
  2293. check_sub(&a.neg(), &b.neg(), d, &m.neg());
  2294. }
  2295. }
  2296. for elm in MUL_TRIPLES.iter() {
  2297. let (a_vec, b_vec, c_vec) = *elm;
  2298. let a = BigInt::from_slice(Plus, a_vec);
  2299. let b = BigInt::from_slice(Plus, b_vec);
  2300. let c = BigInt::from_slice(Plus, c_vec);
  2301. if !a.is_zero() { check(&c, &a, &b, &Zero::zero()); }
  2302. if !b.is_zero() { check(&c, &b, &a, &Zero::zero()); }
  2303. }
  2304. for elm in DIV_REM_QUADRUPLES.iter() {
  2305. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  2306. let a = BigInt::from_slice(Plus, a_vec);
  2307. let b = BigInt::from_slice(Plus, b_vec);
  2308. let c = BigInt::from_slice(Plus, c_vec);
  2309. let d = BigInt::from_slice(Plus, d_vec);
  2310. if !b.is_zero() {
  2311. check(&a, &b, &c, &d);
  2312. }
  2313. }
  2314. }
  2315. #[test]
  2316. fn test_div_rem() {
  2317. fn check_sub(a: &BigInt, b: &BigInt, ans_q: &BigInt, ans_r: &BigInt) {
  2318. let (q, r) = a.div_rem(b);
  2319. if !r.is_zero() {
  2320. assert_eq!(r.sign, a.sign);
  2321. }
  2322. assert!(r.abs() <= b.abs());
  2323. assert!(*a == (*b) * q + r);
  2324. assert!(q == *ans_q);
  2325. assert!(r == *ans_r);
  2326. }
  2327. fn check(a: &BigInt, b: &BigInt, q: &BigInt, r: &BigInt) {
  2328. check_sub(a, b, q, r);
  2329. check_sub(a, &b.neg(), &q.neg(), r);
  2330. check_sub(&a.neg(), b, &q.neg(), &r.neg());
  2331. check_sub(&a.neg(), &b.neg(), q, &r.neg());
  2332. }
  2333. for elm in MUL_TRIPLES.iter() {
  2334. let (a_vec, b_vec, c_vec) = *elm;
  2335. let a = BigInt::from_slice(Plus, a_vec);
  2336. let b = BigInt::from_slice(Plus, b_vec);
  2337. let c = BigInt::from_slice(Plus, c_vec);
  2338. if !a.is_zero() { check(&c, &a, &b, &Zero::zero()); }
  2339. if !b.is_zero() { check(&c, &b, &a, &Zero::zero()); }
  2340. }
  2341. for elm in DIV_REM_QUADRUPLES.iter() {
  2342. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  2343. let a = BigInt::from_slice(Plus, a_vec);
  2344. let b = BigInt::from_slice(Plus, b_vec);
  2345. let c = BigInt::from_slice(Plus, c_vec);
  2346. let d = BigInt::from_slice(Plus, d_vec);
  2347. if !b.is_zero() {
  2348. check(&a, &b, &c, &d);
  2349. }
  2350. }
  2351. }
  2352. #[test]
  2353. fn test_checked_add() {
  2354. for elm in SUM_TRIPLES.iter() {
  2355. let (a_vec, b_vec, c_vec) = *elm;
  2356. let a = BigInt::from_slice(Plus, a_vec);
  2357. let b = BigInt::from_slice(Plus, b_vec);
  2358. let c = BigInt::from_slice(Plus, c_vec);
  2359. assert!(a.checked_add(&b).unwrap() == c);
  2360. assert!(b.checked_add(&a).unwrap() == c);
  2361. assert!(c.checked_add(&(-a)).unwrap() == b);
  2362. assert!(c.checked_add(&(-b)).unwrap() == a);
  2363. assert!(a.checked_add(&(-c)).unwrap() == (-b));
  2364. assert!(b.checked_add(&(-c)).unwrap() == (-a));
  2365. assert!((-a).checked_add(&(-b)).unwrap() == (-c))
  2366. assert!(a.checked_add(&(-a)).unwrap() == Zero::zero());
  2367. }
  2368. }
  2369. #[test]
  2370. fn test_checked_sub() {
  2371. for elm in SUM_TRIPLES.iter() {
  2372. let (a_vec, b_vec, c_vec) = *elm;
  2373. let a = BigInt::from_slice(Plus, a_vec);
  2374. let b = BigInt::from_slice(Plus, b_vec);
  2375. let c = BigInt::from_slice(Plus, c_vec);
  2376. assert!(c.checked_sub(&a).unwrap() == b);
  2377. assert!(c.checked_sub(&b).unwrap() == a);
  2378. assert!((-b).checked_sub(&a).unwrap() == (-c))
  2379. assert!((-a).checked_sub(&b).unwrap() == (-c))
  2380. assert!(b.checked_sub(&(-a)).unwrap() == c);
  2381. assert!(a.checked_sub(&(-b)).unwrap() == c);
  2382. assert!((-c).checked_sub(&(-a)).unwrap() == (-b));
  2383. assert!(a.checked_sub(&a).unwrap() == Zero::zero());
  2384. }
  2385. }
  2386. #[test]
  2387. fn test_checked_mul() {
  2388. for elm in MUL_TRIPLES.iter() {
  2389. let (a_vec, b_vec, c_vec) = *elm;
  2390. let a = BigInt::from_slice(Plus, a_vec);
  2391. let b = BigInt::from_slice(Plus, b_vec);
  2392. let c = BigInt::from_slice(Plus, c_vec);
  2393. assert!(a.checked_mul(&b).unwrap() == c);
  2394. assert!(b.checked_mul(&a).unwrap() == c);
  2395. assert!((-a).checked_mul(&b).unwrap() == -c);
  2396. assert!((-b).checked_mul(&a).unwrap() == -c);
  2397. }
  2398. for elm in DIV_REM_QUADRUPLES.iter() {
  2399. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  2400. let a = BigInt::from_slice(Plus, a_vec);
  2401. let b = BigInt::from_slice(Plus, b_vec);
  2402. let c = BigInt::from_slice(Plus, c_vec);
  2403. let d = BigInt::from_slice(Plus, d_vec);
  2404. assert!(a == b.checked_mul(&c).unwrap() + d);
  2405. assert!(a == c.checked_mul(&b).unwrap() + d);
  2406. }
  2407. }
  2408. #[test]
  2409. fn test_checked_div() {
  2410. for elm in MUL_TRIPLES.iter() {
  2411. let (a_vec, b_vec, c_vec) = *elm;
  2412. let a = BigInt::from_slice(Plus, a_vec);
  2413. let b = BigInt::from_slice(Plus, b_vec);
  2414. let c = BigInt::from_slice(Plus, c_vec);
  2415. if !a.is_zero() {
  2416. assert!(c.checked_div(&a).unwrap() == b);
  2417. assert!((-c).checked_div(&(-a)).unwrap() == b);
  2418. assert!((-c).checked_div(&a).unwrap() == -b);
  2419. }
  2420. if !b.is_zero() {
  2421. assert!(c.checked_div(&b).unwrap() == a);
  2422. assert!((-c).checked_div(&(-b)).unwrap() == a);
  2423. assert!((-c).checked_div(&b).unwrap() == -a);
  2424. }
  2425. assert!(c.checked_div(&Zero::zero()).is_none());
  2426. assert!((-c).checked_div(&Zero::zero()).is_none());
  2427. }
  2428. }
  2429. #[test]
  2430. fn test_gcd() {
  2431. fn check(a: int, b: int, c: int) {
  2432. let big_a: BigInt = FromPrimitive::from_int(a).unwrap();
  2433. let big_b: BigInt = FromPrimitive::from_int(b).unwrap();
  2434. let big_c: BigInt = FromPrimitive::from_int(c).unwrap();
  2435. assert_eq!(big_a.gcd(&big_b), big_c);
  2436. }
  2437. check(10, 2, 2);
  2438. check(10, 3, 1);
  2439. check(0, 3, 3);
  2440. check(3, 3, 3);
  2441. check(56, 42, 14);
  2442. check(3, -3, 3);
  2443. check(-6, 3, 3);
  2444. check(-4, -2, 2);
  2445. }
  2446. #[test]
  2447. fn test_lcm() {
  2448. fn check(a: int, b: int, c: int) {
  2449. let big_a: BigInt = FromPrimitive::from_int(a).unwrap();
  2450. let big_b: BigInt = FromPrimitive::from_int(b).unwrap();
  2451. let big_c: BigInt = FromPrimitive::from_int(c).unwrap();
  2452. assert_eq!(big_a.lcm(&big_b), big_c);
  2453. }
  2454. check(1, 0, 0);
  2455. check(0, 1, 0);
  2456. check(1, 1, 1);
  2457. check(-1, 1, 1);
  2458. check(1, -1, 1);
  2459. check(-1, -1, 1);
  2460. check(8, 9, 72);
  2461. check(11, 5, 55);
  2462. }
  2463. #[test]
  2464. fn test_abs_sub() {
  2465. let zero: BigInt = Zero::zero();
  2466. let one: BigInt = One::one();
  2467. assert_eq!((-one).abs_sub(&one), zero);
  2468. let one: BigInt = One::one();
  2469. let zero: BigInt = Zero::zero();
  2470. assert_eq!(one.abs_sub(&one), zero);
  2471. let one: BigInt = One::one();
  2472. let zero: BigInt = Zero::zero();
  2473. assert_eq!(one.abs_sub(&zero), one);
  2474. let one: BigInt = One::one();
  2475. let two: BigInt = FromPrimitive::from_int(2).unwrap();
  2476. assert_eq!(one.abs_sub(&-one), two);
  2477. }
  2478. #[test]
  2479. fn test_from_str_radix() {
  2480. fn check(s: &str, ans: Option<int>) {
  2481. let ans = ans.map(|n| {
  2482. let x: BigInt = FromPrimitive::from_int(n).unwrap();
  2483. x
  2484. });
  2485. assert_eq!(FromStrRadix::from_str_radix(s, 10), ans);
  2486. }
  2487. check("10", Some(10));
  2488. check("1", Some(1));
  2489. check("0", Some(0));
  2490. check("-1", Some(-1));
  2491. check("-10", Some(-10));
  2492. check("Z", None);
  2493. check("_", None);
  2494. // issue 10522, this hit an edge case that caused it to
  2495. // attempt to allocate a vector of size (-1u) == huge.
  2496. let x: BigInt =
  2497. from_str(format!("1{}", "0".repeat(36)).as_slice()).unwrap();
  2498. let _y = x.to_string();
  2499. }
  2500. #[test]
  2501. fn test_neg() {
  2502. assert!(-BigInt::new(Plus, vec!(1, 1, 1)) ==
  2503. BigInt::new(Minus, vec!(1, 1, 1)));
  2504. assert!(-BigInt::new(Minus, vec!(1, 1, 1)) ==
  2505. BigInt::new(Plus, vec!(1, 1, 1)));
  2506. let zero: BigInt = Zero::zero();
  2507. assert_eq!(-zero, zero);
  2508. }
  2509. #[test]
  2510. fn test_rand() {
  2511. let mut rng = task_rng();
  2512. let _n: BigInt = rng.gen_bigint(137);
  2513. assert!(rng.gen_bigint(0).is_zero());
  2514. }
  2515. #[test]
  2516. fn test_rand_range() {
  2517. let mut rng = task_rng();
  2518. for _ in range(0u, 10) {
  2519. assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_uint(236).unwrap(),
  2520. &FromPrimitive::from_uint(237).unwrap()),
  2521. FromPrimitive::from_uint(236).unwrap());
  2522. }
  2523. fn check(l: BigInt, u: BigInt) {
  2524. let mut rng = task_rng();
  2525. for _ in range(0u, 1000) {
  2526. let n: BigInt = rng.gen_bigint_range(&l, &u);
  2527. assert!(n >= l);
  2528. assert!(n < u);
  2529. }
  2530. }
  2531. let l: BigInt = FromPrimitive::from_uint(403469000 + 2352).unwrap();
  2532. let u: BigInt = FromPrimitive::from_uint(403469000 + 3513).unwrap();
  2533. check( l.clone(), u.clone());
  2534. check(-l.clone(), u.clone());
  2535. check(-u.clone(), -l.clone());
  2536. }
  2537. #[test]
  2538. #[should_fail]
  2539. fn test_zero_rand_range() {
  2540. task_rng().gen_bigint_range(&FromPrimitive::from_int(54).unwrap(),
  2541. &FromPrimitive::from_int(54).unwrap());
  2542. }
  2543. #[test]
  2544. #[should_fail]
  2545. fn test_negative_rand_range() {
  2546. let mut rng = task_rng();
  2547. let l = FromPrimitive::from_uint(2352).unwrap();
  2548. let u = FromPrimitive::from_uint(3513).unwrap();
  2549. // Switching u and l should fail:
  2550. let _n: BigInt = rng.gen_bigint_range(&u, &l);
  2551. }
  2552. }
  2553. #[cfg(test)]
  2554. mod bench {
  2555. extern crate test;
  2556. use self::test::Bencher;
  2557. use super::BigUint;
  2558. use std::iter;
  2559. use std::mem::replace;
  2560. use std::num::{FromPrimitive, Zero, One};
  2561. fn factorial(n: uint) -> BigUint {
  2562. let mut f: BigUint = One::one();
  2563. for i in iter::range_inclusive(1, n) {
  2564. f = f * FromPrimitive::from_uint(i).unwrap();
  2565. }
  2566. f
  2567. }
  2568. fn fib(n: uint) -> BigUint {
  2569. let mut f0: BigUint = Zero::zero();
  2570. let mut f1: BigUint = One::one();
  2571. for _ in range(0, n) {
  2572. let f2 = f0 + f1;
  2573. f0 = replace(&mut f1, f2);
  2574. }
  2575. f0
  2576. }
  2577. #[bench]
  2578. fn factorial_100(b: &mut Bencher) {
  2579. b.iter(|| {
  2580. factorial(100);
  2581. });
  2582. }
  2583. #[bench]
  2584. fn fib_100(b: &mut Bencher) {
  2585. b.iter(|| {
  2586. fib(100);
  2587. });
  2588. }
  2589. #[bench]
  2590. fn to_string(b: &mut Bencher) {
  2591. let fac = factorial(100);
  2592. let fib = fib(100);
  2593. b.iter(|| {
  2594. fac.to_string();
  2595. });
  2596. b.iter(|| {
  2597. fib.to_string();
  2598. });
  2599. }
  2600. #[bench]
  2601. fn shr(b: &mut Bencher) {
  2602. let n = { let one : BigUint = One::one(); one << 1000 };
  2603. b.iter(|| {
  2604. let mut m = n.clone();
  2605. for _ in range(0u, 10) {
  2606. m = m >> 1;
  2607. }
  2608. })
  2609. }
  2610. }