bigint.rs 89 KB

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