bigint.rs 90 KB

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