bigint.rs 94 KB

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