bigint.rs 104 KB

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