bigint.rs 147 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733
  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 a vector 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. use Integer;
  60. use std::default::Default;
  61. use std::error::Error;
  62. use std::iter::repeat;
  63. use std::num::ParseIntError;
  64. use std::ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Neg, Rem, Shl, Shr, Sub};
  65. use std::str::{self, FromStr};
  66. use std::fmt;
  67. use std::cmp::Ordering::{self, Less, Greater, Equal};
  68. use std::{f32, f64};
  69. use std::{u8, i64, u64};
  70. use rand::Rng;
  71. use traits::{ToPrimitive, FromPrimitive};
  72. use traits::Float;
  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. #[allow(non_snake_case)]
  82. pub mod big_digit {
  83. use super::BigDigit;
  84. use super::DoubleBigDigit;
  85. // `DoubleBigDigit` size dependent
  86. pub const BITS: usize = 32;
  87. pub const BASE: DoubleBigDigit = 1 << BITS;
  88. const LO_MASK: DoubleBigDigit = (-1i32 as DoubleBigDigit) >> BITS;
  89. #[inline]
  90. fn get_hi(n: DoubleBigDigit) -> BigDigit { (n >> BITS) as BigDigit }
  91. #[inline]
  92. fn get_lo(n: DoubleBigDigit) -> BigDigit { (n & LO_MASK) as BigDigit }
  93. /// Split one `DoubleBigDigit` into two `BigDigit`s.
  94. #[inline]
  95. pub fn from_doublebigdigit(n: DoubleBigDigit) -> (BigDigit, BigDigit) {
  96. (get_hi(n), get_lo(n))
  97. }
  98. /// Join two `BigDigit`s into one `DoubleBigDigit`
  99. #[inline]
  100. pub fn to_doublebigdigit(hi: BigDigit, lo: BigDigit) -> DoubleBigDigit {
  101. (lo as DoubleBigDigit) | ((hi as DoubleBigDigit) << BITS)
  102. }
  103. }
  104. /*
  105. * Generic functions for add/subtract/multiply with carry/borrow:
  106. */
  107. // Add with carry:
  108. #[inline]
  109. fn adc(a: BigDigit, b: BigDigit, carry: &mut BigDigit) -> BigDigit {
  110. let (hi, lo) = big_digit::from_doublebigdigit(
  111. (a as DoubleBigDigit) +
  112. (b as DoubleBigDigit) +
  113. (*carry as DoubleBigDigit));
  114. *carry = hi;
  115. lo
  116. }
  117. // Subtract with borrow:
  118. #[inline]
  119. fn sbb(a: BigDigit, b: BigDigit, borrow: &mut BigDigit) -> BigDigit {
  120. let (hi, lo) = big_digit::from_doublebigdigit(
  121. big_digit::BASE
  122. + (a as DoubleBigDigit)
  123. - (b as DoubleBigDigit)
  124. - (*borrow as DoubleBigDigit));
  125. /*
  126. hi * (base) + lo == 1*(base) + ai - bi - borrow
  127. => ai - bi - borrow < 0 <=> hi == 0
  128. */
  129. *borrow = if hi == 0 { 1 } else { 0 };
  130. lo
  131. }
  132. #[inline]
  133. fn mac_with_carry(a: BigDigit, b: BigDigit, c: BigDigit, carry: &mut BigDigit) -> BigDigit {
  134. let (hi, lo) = big_digit::from_doublebigdigit(
  135. (a as DoubleBigDigit) +
  136. (b as DoubleBigDigit) * (c as DoubleBigDigit) +
  137. (*carry as DoubleBigDigit));
  138. *carry = hi;
  139. lo
  140. }
  141. /// Divide a two digit numerator by a one digit divisor, returns quotient and remainder:
  142. ///
  143. /// Note: the caller must ensure that both the quotient and remainder will fit into a single digit.
  144. /// This is _not_ true for an arbitrary numerator/denominator.
  145. ///
  146. /// (This function also matches what the x86 divide instruction does).
  147. #[inline]
  148. fn div_wide(hi: BigDigit, lo: BigDigit, divisor: BigDigit) -> (BigDigit, BigDigit) {
  149. debug_assert!(hi < divisor);
  150. let lhs = big_digit::to_doublebigdigit(hi, lo);
  151. let rhs = divisor as DoubleBigDigit;
  152. ((lhs / rhs) as BigDigit, (lhs % rhs) as BigDigit)
  153. }
  154. /// A big unsigned integer type.
  155. ///
  156. /// A `BigUint`-typed value `BigUint { data: vec!(a, b, c) }` represents a number
  157. /// `(a + b * big_digit::BASE + c * big_digit::BASE^2)`.
  158. #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash)]
  159. pub struct BigUint {
  160. data: Vec<BigDigit>
  161. }
  162. impl PartialEq for BigUint {
  163. #[inline]
  164. fn eq(&self, other: &BigUint) -> bool {
  165. match self.cmp(other) { Equal => true, _ => false }
  166. }
  167. }
  168. impl Eq for BigUint {}
  169. impl PartialOrd for BigUint {
  170. #[inline]
  171. fn partial_cmp(&self, other: &BigUint) -> Option<Ordering> {
  172. Some(self.cmp(other))
  173. }
  174. }
  175. fn cmp_slice(a: &[BigDigit], b: &[BigDigit]) -> Ordering {
  176. debug_assert!(a.last() != Some(&0));
  177. debug_assert!(b.last() != Some(&0));
  178. let (a_len, b_len) = (a.len(), b.len());
  179. if a_len < b_len { return Less; }
  180. if a_len > b_len { return Greater; }
  181. for (&ai, &bi) in a.iter().rev().zip(b.iter().rev()) {
  182. if ai < bi { return Less; }
  183. if ai > bi { return Greater; }
  184. }
  185. return Equal;
  186. }
  187. impl Ord for BigUint {
  188. #[inline]
  189. fn cmp(&self, other: &BigUint) -> Ordering {
  190. cmp_slice(&self.data[..], &other.data[..])
  191. }
  192. }
  193. impl Default for BigUint {
  194. #[inline]
  195. fn default() -> BigUint { Zero::zero() }
  196. }
  197. impl fmt::Display for BigUint {
  198. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  199. write!(f, "{}", self.to_str_radix(10))
  200. }
  201. }
  202. impl FromStr for BigUint {
  203. type Err = ParseBigIntError;
  204. #[inline]
  205. fn from_str(s: &str) -> Result<BigUint, ParseBigIntError> {
  206. BigUint::from_str_radix(s, 10)
  207. }
  208. }
  209. // Read bitwise digits that evenly divide BigDigit
  210. fn from_bitwise_digits_le(v: &[u8], bits: usize) -> BigUint {
  211. debug_assert!(!v.is_empty() && bits <= 8 && big_digit::BITS % bits == 0);
  212. debug_assert!(v.iter().all(|&c| (c as BigDigit) < (1 << bits)));
  213. let digits_per_big_digit = big_digit::BITS / bits;
  214. let data = v.chunks(digits_per_big_digit).map(|chunk| {
  215. chunk.iter().rev().fold(0u32, |acc, &c| (acc << bits) | c as BigDigit)
  216. }).collect();
  217. BigUint::new(data)
  218. }
  219. // Read bitwise digits that don't evenly divide BigDigit
  220. fn from_inexact_bitwise_digits_le(v: &[u8], bits: usize) -> BigUint {
  221. debug_assert!(!v.is_empty() && bits <= 8 && big_digit::BITS % bits != 0);
  222. debug_assert!(v.iter().all(|&c| (c as BigDigit) < (1 << bits)));
  223. let big_digits = (v.len() * bits + big_digit::BITS - 1) / big_digit::BITS;
  224. let mut data = Vec::with_capacity(big_digits);
  225. let mut d = 0;
  226. let mut dbits = 0;
  227. for &c in v {
  228. d |= (c as DoubleBigDigit) << dbits;
  229. dbits += bits;
  230. if dbits >= big_digit::BITS {
  231. let (hi, lo) = big_digit::from_doublebigdigit(d);
  232. data.push(lo);
  233. d = hi as DoubleBigDigit;
  234. dbits -= big_digit::BITS;
  235. }
  236. }
  237. if dbits > 0 {
  238. debug_assert!(dbits < big_digit::BITS);
  239. data.push(d as BigDigit);
  240. }
  241. BigUint::new(data)
  242. }
  243. // Read little-endian radix digits
  244. fn from_radix_digits_be(v: &[u8], radix: u32) -> BigUint {
  245. debug_assert!(!v.is_empty() && !radix.is_power_of_two());
  246. debug_assert!(v.iter().all(|&c| (c as u32) < radix));
  247. // Estimate how big the result will be, so we can pre-allocate it.
  248. let bits = (radix as f64).log2() * v.len() as f64;
  249. let big_digits = (bits / big_digit::BITS as f64).ceil();
  250. let mut data = Vec::with_capacity(big_digits as usize);
  251. let (base, power) = get_radix_base(radix);
  252. debug_assert!(base < (1 << 32));
  253. let base = base as BigDigit;
  254. let r = v.len() % power;
  255. let i = if r == 0 { power } else { r };
  256. let (head, tail) = v.split_at(i);
  257. let first = head.iter().fold(0, |acc, &d| acc * radix + d as BigDigit);
  258. data.push(first);
  259. debug_assert!(tail.len() % power == 0);
  260. for chunk in tail.chunks(power) {
  261. if data.last() != Some(&0) {
  262. data.push(0);
  263. }
  264. let mut carry = 0;
  265. for d in data.iter_mut() {
  266. *d = mac_with_carry(0, *d, base, &mut carry);
  267. }
  268. debug_assert!(carry == 0);
  269. let n = chunk.iter().fold(0, |acc, &d| acc * radix + d as BigDigit);
  270. add2(&mut data, &[n]);
  271. }
  272. BigUint::new(data)
  273. }
  274. impl Num for BigUint {
  275. type FromStrRadixErr = ParseBigIntError;
  276. /// Creates and initializes a `BigUint`.
  277. fn from_str_radix(s: &str, radix: u32) -> Result<BigUint, ParseBigIntError> {
  278. assert!(2 <= radix && radix <= 36, "The radix must be within 2...36");
  279. if s.is_empty() {
  280. // create ParseIntError::Empty
  281. let e = u64::from_str_radix(s, radix).unwrap_err();
  282. return Err(e.into());
  283. }
  284. // First normalize all characters to plain digit values
  285. let mut v = Vec::with_capacity(s.len());
  286. for b in s.bytes() {
  287. let d = match b {
  288. b'0' ... b'9' => b - b'0',
  289. b'a' ... b'z' => b - b'a' + 10,
  290. b'A' ... b'Z' => b - b'A' + 10,
  291. _ => u8::MAX,
  292. };
  293. if d < radix as u8 {
  294. v.push(d);
  295. } else {
  296. // create ParseIntError::InvalidDigit
  297. let e = u64::from_str_radix(&s[v.len()..], radix).unwrap_err();
  298. return Err(e.into());
  299. }
  300. }
  301. let res = if radix.is_power_of_two() {
  302. // Powers of two can use bitwise masks and shifting instead of multiplication
  303. let bits = radix.trailing_zeros() as usize;
  304. v.reverse();
  305. if big_digit::BITS % bits == 0 {
  306. from_bitwise_digits_le(&v, bits)
  307. } else {
  308. from_inexact_bitwise_digits_le(&v, bits)
  309. }
  310. } else {
  311. from_radix_digits_be(&v, radix)
  312. };
  313. Ok(res)
  314. }
  315. }
  316. macro_rules! forward_val_val_binop {
  317. (impl $imp:ident for $res:ty, $method:ident) => {
  318. impl $imp<$res> for $res {
  319. type Output = $res;
  320. #[inline]
  321. fn $method(self, other: $res) -> $res {
  322. // forward to val-ref
  323. $imp::$method(self, &other)
  324. }
  325. }
  326. }
  327. }
  328. macro_rules! forward_val_val_binop_commutative {
  329. (impl $imp:ident for $res:ty, $method:ident) => {
  330. impl $imp<$res> for $res {
  331. type Output = $res;
  332. #[inline]
  333. fn $method(self, other: $res) -> $res {
  334. // forward to val-ref, with the larger capacity as val
  335. if self.data.capacity() >= other.data.capacity() {
  336. $imp::$method(self, &other)
  337. } else {
  338. $imp::$method(other, &self)
  339. }
  340. }
  341. }
  342. }
  343. }
  344. macro_rules! forward_ref_val_binop {
  345. (impl $imp:ident for $res:ty, $method:ident) => {
  346. impl<'a> $imp<$res> for &'a $res {
  347. type Output = $res;
  348. #[inline]
  349. fn $method(self, other: $res) -> $res {
  350. // forward to ref-ref
  351. $imp::$method(self, &other)
  352. }
  353. }
  354. }
  355. }
  356. macro_rules! forward_ref_val_binop_commutative {
  357. (impl $imp:ident for $res:ty, $method:ident) => {
  358. impl<'a> $imp<$res> for &'a $res {
  359. type Output = $res;
  360. #[inline]
  361. fn $method(self, other: $res) -> $res {
  362. // reverse, forward to val-ref
  363. $imp::$method(other, self)
  364. }
  365. }
  366. }
  367. }
  368. macro_rules! forward_val_ref_binop {
  369. (impl $imp:ident for $res:ty, $method:ident) => {
  370. impl<'a> $imp<&'a $res> for $res {
  371. type Output = $res;
  372. #[inline]
  373. fn $method(self, other: &$res) -> $res {
  374. // forward to ref-ref
  375. $imp::$method(&self, other)
  376. }
  377. }
  378. }
  379. }
  380. macro_rules! forward_ref_ref_binop {
  381. (impl $imp:ident for $res:ty, $method:ident) => {
  382. impl<'a, 'b> $imp<&'b $res> for &'a $res {
  383. type Output = $res;
  384. #[inline]
  385. fn $method(self, other: &$res) -> $res {
  386. // forward to val-ref
  387. $imp::$method(self.clone(), other)
  388. }
  389. }
  390. }
  391. }
  392. macro_rules! forward_ref_ref_binop_commutative {
  393. (impl $imp:ident for $res:ty, $method:ident) => {
  394. impl<'a, 'b> $imp<&'b $res> for &'a $res {
  395. type Output = $res;
  396. #[inline]
  397. fn $method(self, other: &$res) -> $res {
  398. // forward to val-ref, choosing the larger to clone
  399. if self.data.len() >= other.data.len() {
  400. $imp::$method(self.clone(), other)
  401. } else {
  402. $imp::$method(other.clone(), self)
  403. }
  404. }
  405. }
  406. }
  407. }
  408. // Forward everything to ref-ref, when reusing storage is not helpful
  409. macro_rules! forward_all_binop_to_ref_ref {
  410. (impl $imp:ident for $res:ty, $method:ident) => {
  411. forward_val_val_binop!(impl $imp for $res, $method);
  412. forward_val_ref_binop!(impl $imp for $res, $method);
  413. forward_ref_val_binop!(impl $imp for $res, $method);
  414. };
  415. }
  416. // Forward everything to val-ref, so LHS storage can be reused
  417. macro_rules! forward_all_binop_to_val_ref {
  418. (impl $imp:ident for $res:ty, $method:ident) => {
  419. forward_val_val_binop!(impl $imp for $res, $method);
  420. forward_ref_val_binop!(impl $imp for $res, $method);
  421. forward_ref_ref_binop!(impl $imp for $res, $method);
  422. };
  423. }
  424. // Forward everything to val-ref, commutatively, so either LHS or RHS storage can be reused
  425. macro_rules! forward_all_binop_to_val_ref_commutative {
  426. (impl $imp:ident for $res:ty, $method:ident) => {
  427. forward_val_val_binop_commutative!(impl $imp for $res, $method);
  428. forward_ref_val_binop_commutative!(impl $imp for $res, $method);
  429. forward_ref_ref_binop_commutative!(impl $imp for $res, $method);
  430. };
  431. }
  432. forward_all_binop_to_val_ref_commutative!(impl BitAnd for BigUint, bitand);
  433. impl<'a> BitAnd<&'a BigUint> for BigUint {
  434. type Output = BigUint;
  435. #[inline]
  436. fn bitand(self, other: &BigUint) -> BigUint {
  437. let mut data = self.data;
  438. for (ai, &bi) in data.iter_mut().zip(other.data.iter()) {
  439. *ai &= bi;
  440. }
  441. data.truncate(other.data.len());
  442. BigUint::new(data)
  443. }
  444. }
  445. forward_all_binop_to_val_ref_commutative!(impl BitOr for BigUint, bitor);
  446. impl<'a> BitOr<&'a BigUint> for BigUint {
  447. type Output = BigUint;
  448. fn bitor(self, other: &BigUint) -> BigUint {
  449. let mut data = self.data;
  450. for (ai, &bi) in data.iter_mut().zip(other.data.iter()) {
  451. *ai |= bi;
  452. }
  453. if other.data.len() > data.len() {
  454. let extra = &other.data[data.len()..];
  455. data.extend(extra.iter().cloned());
  456. }
  457. BigUint::new(data)
  458. }
  459. }
  460. forward_all_binop_to_val_ref_commutative!(impl BitXor for BigUint, bitxor);
  461. impl<'a> BitXor<&'a BigUint> for BigUint {
  462. type Output = BigUint;
  463. fn bitxor(self, other: &BigUint) -> BigUint {
  464. let mut data = self.data;
  465. for (ai, &bi) in data.iter_mut().zip(other.data.iter()) {
  466. *ai ^= bi;
  467. }
  468. if other.data.len() > data.len() {
  469. let extra = &other.data[data.len()..];
  470. data.extend(extra.iter().cloned());
  471. }
  472. BigUint::new(data)
  473. }
  474. }
  475. impl Shl<usize> for BigUint {
  476. type Output = BigUint;
  477. #[inline]
  478. fn shl(self, rhs: usize) -> BigUint { (&self) << rhs }
  479. }
  480. impl<'a> Shl<usize> for &'a BigUint {
  481. type Output = BigUint;
  482. #[inline]
  483. fn shl(self, rhs: usize) -> BigUint {
  484. let n_unit = rhs / big_digit::BITS;
  485. let n_bits = rhs % big_digit::BITS;
  486. self.shl_unit(n_unit).shl_bits(n_bits)
  487. }
  488. }
  489. impl Shr<usize> for BigUint {
  490. type Output = BigUint;
  491. #[inline]
  492. fn shr(self, rhs: usize) -> BigUint { (&self) >> rhs }
  493. }
  494. impl<'a> Shr<usize> for &'a BigUint {
  495. type Output = BigUint;
  496. #[inline]
  497. fn shr(self, rhs: usize) -> BigUint {
  498. let n_unit = rhs / big_digit::BITS;
  499. let n_bits = rhs % big_digit::BITS;
  500. self.shr_unit(n_unit).shr_bits(n_bits)
  501. }
  502. }
  503. impl Zero for BigUint {
  504. #[inline]
  505. fn zero() -> BigUint { BigUint::new(Vec::new()) }
  506. #[inline]
  507. fn is_zero(&self) -> bool { self.data.is_empty() }
  508. }
  509. impl One for BigUint {
  510. #[inline]
  511. fn one() -> BigUint { BigUint::new(vec!(1)) }
  512. }
  513. impl Unsigned for BigUint {}
  514. forward_all_binop_to_val_ref_commutative!(impl Add for BigUint, add);
  515. // Only for the Add impl:
  516. #[must_use]
  517. #[inline]
  518. fn __add2(a: &mut [BigDigit], b: &[BigDigit]) -> BigDigit {
  519. let mut b_iter = b.iter();
  520. let mut carry = 0;
  521. for ai in a.iter_mut() {
  522. if let Some(bi) = b_iter.next() {
  523. *ai = adc(*ai, *bi, &mut carry);
  524. } else if carry != 0 {
  525. *ai = adc(*ai, 0, &mut carry);
  526. } else {
  527. break;
  528. }
  529. }
  530. debug_assert!(b_iter.next() == None);
  531. carry
  532. }
  533. /// /Two argument addition of raw slices:
  534. /// a += b
  535. ///
  536. /// The caller _must_ ensure that a is big enough to store the result - typically this means
  537. /// resizing a to max(a.len(), b.len()) + 1, to fit a possible carry.
  538. fn add2(a: &mut [BigDigit], b: &[BigDigit]) {
  539. let carry = __add2(a, b);
  540. debug_assert!(carry == 0);
  541. }
  542. /*
  543. * We'd really prefer to avoid using add2/sub2 directly as much as possible - since they make the
  544. * caller entirely responsible for ensuring a's vector is big enough, and that the result is
  545. * normalized, they're rather error prone and verbose:
  546. *
  547. * We could implement the Add and Sub traits for BigUint + BigDigit slices, like below - this works
  548. * great, except that then it becomes the module's public interface, which we probably don't want:
  549. *
  550. * I'm keeping the code commented out, because I think this is worth revisiting:
  551. impl<'a> Add<&'a [BigDigit]> for BigUint {
  552. type Output = BigUint;
  553. fn add(mut self, other: &[BigDigit]) -> BigUint {
  554. if self.data.len() < other.len() {
  555. let extra = other.len() - self.data.len();
  556. self.data.extend(repeat(0).take(extra));
  557. }
  558. let carry = __add2(&mut self.data[..], other);
  559. if carry != 0 {
  560. self.data.push(carry);
  561. }
  562. self
  563. }
  564. }
  565. */
  566. impl<'a> Add<&'a BigUint> for BigUint {
  567. type Output = BigUint;
  568. fn add(mut self, other: &BigUint) -> BigUint {
  569. if self.data.len() < other.data.len() {
  570. let extra = other.data.len() - self.data.len();
  571. self.data.extend(repeat(0).take(extra));
  572. }
  573. let carry = __add2(&mut self.data[..], &other.data[..]);
  574. if carry != 0 {
  575. self.data.push(carry);
  576. }
  577. self
  578. }
  579. }
  580. forward_all_binop_to_val_ref!(impl Sub for BigUint, sub);
  581. fn sub2(a: &mut [BigDigit], b: &[BigDigit]) {
  582. let mut b_iter = b.iter();
  583. let mut borrow = 0;
  584. for ai in a.iter_mut() {
  585. if let Some(bi) = b_iter.next() {
  586. *ai = sbb(*ai, *bi, &mut borrow);
  587. } else if borrow != 0 {
  588. *ai = sbb(*ai, 0, &mut borrow);
  589. } else {
  590. break;
  591. }
  592. }
  593. /* note: we're _required_ to fail on underflow */
  594. assert!(borrow == 0 && b_iter.all(|x| *x == 0),
  595. "Cannot subtract b from a because b is larger than a.");
  596. }
  597. impl<'a> Sub<&'a BigUint> for BigUint {
  598. type Output = BigUint;
  599. fn sub(mut self, other: &BigUint) -> BigUint {
  600. sub2(&mut self.data[..], &other.data[..]);
  601. self.normalize()
  602. }
  603. }
  604. fn sub_sign(a: &[BigDigit], b: &[BigDigit]) -> BigInt {
  605. // Normalize:
  606. let a = &a[..a.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)];
  607. let b = &b[..b.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)];
  608. match cmp_slice(a, b) {
  609. Greater => {
  610. let mut ret = BigUint::from_slice(a);
  611. sub2(&mut ret.data[..], b);
  612. BigInt::from_biguint(Plus, ret.normalize())
  613. },
  614. Less => {
  615. let mut ret = BigUint::from_slice(b);
  616. sub2(&mut ret.data[..], a);
  617. BigInt::from_biguint(Minus, ret.normalize())
  618. },
  619. _ => Zero::zero(),
  620. }
  621. }
  622. forward_all_binop_to_ref_ref!(impl Mul for BigUint, mul);
  623. /// Three argument multiply accumulate:
  624. /// acc += b * c
  625. fn mac_digit(acc: &mut [BigDigit], b: &[BigDigit], c: BigDigit) {
  626. if c == 0 { return; }
  627. let mut b_iter = b.iter();
  628. let mut carry = 0;
  629. for ai in acc.iter_mut() {
  630. if let Some(bi) = b_iter.next() {
  631. *ai = mac_with_carry(*ai, *bi, c, &mut carry);
  632. } else if carry != 0 {
  633. *ai = mac_with_carry(*ai, 0, c, &mut carry);
  634. } else {
  635. break;
  636. }
  637. }
  638. assert!(carry == 0);
  639. }
  640. /// Three argument multiply accumulate:
  641. /// acc += b * c
  642. fn mac3(acc: &mut [BigDigit], b: &[BigDigit], c: &[BigDigit]) {
  643. let (x, y) = if b.len() < c.len() { (b, c) } else { (c, b) };
  644. /*
  645. * Karatsuba multiplication is slower than long multiplication for small x and y:
  646. */
  647. if x.len() <= 4 {
  648. for (i, xi) in x.iter().enumerate() {
  649. mac_digit(&mut acc[i..], y, *xi);
  650. }
  651. } else {
  652. /*
  653. * Karatsuba multiplication:
  654. *
  655. * The idea is that we break x and y up into two smaller numbers that each have about half
  656. * as many digits, like so (note that multiplying by b is just a shift):
  657. *
  658. * x = x0 + x1 * b
  659. * y = y0 + y1 * b
  660. *
  661. * With some algebra, we can compute x * y with three smaller products, where the inputs to
  662. * each of the smaller products have only about half as many digits as x and y:
  663. *
  664. * x * y = (x0 + x1 * b) * (y0 + y1 * b)
  665. *
  666. * x * y = x0 * y0
  667. * + x0 * y1 * b
  668. * + x1 * y0 * b
  669. * + x1 * y1 * b^2
  670. *
  671. * Let p0 = x0 * y0 and p2 = x1 * y1:
  672. *
  673. * x * y = p0
  674. * + (x0 * y1 + x1 * p0) * b
  675. * + p2 * b^2
  676. *
  677. * The real trick is that middle term:
  678. *
  679. * x0 * y1 + x1 * y0
  680. *
  681. * = x0 * y1 + x1 * y0 - p0 + p0 - p2 + p2
  682. *
  683. * = x0 * y1 + x1 * y0 - x0 * y0 - x1 * y1 + p0 + p2
  684. *
  685. * Now we complete the square:
  686. *
  687. * = -(x0 * y0 - x0 * y1 - x1 * y0 + x1 * y1) + p0 + p2
  688. *
  689. * = -((x1 - x0) * (y1 - y0)) + p0 + p2
  690. *
  691. * Let p1 = (x1 - x0) * (y1 - y0), and substitute back into our original formula:
  692. *
  693. * x * y = p0
  694. * + (p0 + p2 - p1) * b
  695. * + p2 * b^2
  696. *
  697. * Where the three intermediate products are:
  698. *
  699. * p0 = x0 * y0
  700. * p1 = (x1 - x0) * (y1 - y0)
  701. * p2 = x1 * y1
  702. *
  703. * In doing the computation, we take great care to avoid unnecessary temporary variables
  704. * (since creating a BigUint requires a heap allocation): thus, we rearrange the formula a
  705. * bit so we can use the same temporary variable for all the intermediate products:
  706. *
  707. * x * y = p2 * b^2 + p2 * b
  708. * + p0 * b + p0
  709. * - p1 * b
  710. *
  711. * The other trick we use is instead of doing explicit shifts, we slice acc at the
  712. * appropriate offset when doing the add.
  713. */
  714. /*
  715. * When x is smaller than y, it's significantly faster to pick b such that x is split in
  716. * half, not y:
  717. */
  718. let b = x.len() / 2;
  719. let (x0, x1) = x.split_at(b);
  720. let (y0, y1) = y.split_at(b);
  721. /* We reuse the same BigUint for all the intermediate multiplies: */
  722. let len = y.len() + 1;
  723. let mut p = BigUint { data: vec![0; len] };
  724. // p2 = x1 * y1
  725. mac3(&mut p.data[..], x1, y1);
  726. // Not required, but the adds go faster if we drop any unneeded 0s from the end:
  727. p = p.normalize();
  728. add2(&mut acc[b..], &p.data[..]);
  729. add2(&mut acc[b * 2..], &p.data[..]);
  730. // Zero out p before the next multiply:
  731. p.data.truncate(0);
  732. p.data.extend(repeat(0).take(len));
  733. // p0 = x0 * y0
  734. mac3(&mut p.data[..], x0, y0);
  735. p = p.normalize();
  736. add2(&mut acc[..], &p.data[..]);
  737. add2(&mut acc[b..], &p.data[..]);
  738. // p1 = (x1 - x0) * (y1 - y0)
  739. // We do this one last, since it may be negative and acc can't ever be negative:
  740. let j0 = sub_sign(x1, x0);
  741. let j1 = sub_sign(y1, y0);
  742. match j0.sign * j1.sign {
  743. Plus => {
  744. p.data.truncate(0);
  745. p.data.extend(repeat(0).take(len));
  746. mac3(&mut p.data[..], &j0.data.data[..], &j1.data.data[..]);
  747. p = p.normalize();
  748. sub2(&mut acc[b..], &p.data[..]);
  749. },
  750. Minus => {
  751. mac3(&mut acc[b..], &j0.data.data[..], &j1.data.data[..]);
  752. },
  753. NoSign => (),
  754. }
  755. }
  756. }
  757. fn mul3(x: &[BigDigit], y: &[BigDigit]) -> BigUint {
  758. let len = x.len() + y.len() + 1;
  759. let mut prod = BigUint { data: vec![0; len] };
  760. mac3(&mut prod.data[..], x, y);
  761. prod.normalize()
  762. }
  763. impl<'a, 'b> Mul<&'b BigUint> for &'a BigUint {
  764. type Output = BigUint;
  765. #[inline]
  766. fn mul(self, other: &BigUint) -> BigUint {
  767. mul3(&self.data[..], &other.data[..])
  768. }
  769. }
  770. fn div_rem_digit(mut a: BigUint, b: BigDigit) -> (BigUint, BigDigit) {
  771. let mut rem = 0;
  772. for d in a.data.iter_mut().rev() {
  773. let (q, r) = div_wide(rem, *d, b);
  774. *d = q;
  775. rem = r;
  776. }
  777. (a.normalize(), rem)
  778. }
  779. forward_all_binop_to_ref_ref!(impl Div for BigUint, div);
  780. impl<'a, 'b> Div<&'b BigUint> for &'a BigUint {
  781. type Output = BigUint;
  782. #[inline]
  783. fn div(self, other: &BigUint) -> BigUint {
  784. let (q, _) = self.div_rem(other);
  785. return q;
  786. }
  787. }
  788. forward_all_binop_to_ref_ref!(impl Rem for BigUint, rem);
  789. impl<'a, 'b> Rem<&'b BigUint> for &'a BigUint {
  790. type Output = BigUint;
  791. #[inline]
  792. fn rem(self, other: &BigUint) -> BigUint {
  793. let (_, r) = self.div_rem(other);
  794. return r;
  795. }
  796. }
  797. impl Neg for BigUint {
  798. type Output = BigUint;
  799. #[inline]
  800. fn neg(self) -> BigUint { panic!() }
  801. }
  802. impl<'a> Neg for &'a BigUint {
  803. type Output = BigUint;
  804. #[inline]
  805. fn neg(self) -> BigUint { panic!() }
  806. }
  807. impl CheckedAdd for BigUint {
  808. #[inline]
  809. fn checked_add(&self, v: &BigUint) -> Option<BigUint> {
  810. return Some(self.add(v));
  811. }
  812. }
  813. impl CheckedSub for BigUint {
  814. #[inline]
  815. fn checked_sub(&self, v: &BigUint) -> Option<BigUint> {
  816. match self.cmp(v) {
  817. Less => None,
  818. Equal => Some(Zero::zero()),
  819. Greater => Some(self.sub(v)),
  820. }
  821. }
  822. }
  823. impl CheckedMul for BigUint {
  824. #[inline]
  825. fn checked_mul(&self, v: &BigUint) -> Option<BigUint> {
  826. return Some(self.mul(v));
  827. }
  828. }
  829. impl CheckedDiv for BigUint {
  830. #[inline]
  831. fn checked_div(&self, v: &BigUint) -> Option<BigUint> {
  832. if v.is_zero() {
  833. return None;
  834. }
  835. return Some(self.div(v));
  836. }
  837. }
  838. impl Integer for BigUint {
  839. #[inline]
  840. fn div_rem(&self, other: &BigUint) -> (BigUint, BigUint) {
  841. self.div_mod_floor(other)
  842. }
  843. #[inline]
  844. fn div_floor(&self, other: &BigUint) -> BigUint {
  845. let (d, _) = self.div_mod_floor(other);
  846. return d;
  847. }
  848. #[inline]
  849. fn mod_floor(&self, other: &BigUint) -> BigUint {
  850. let (_, m) = self.div_mod_floor(other);
  851. return m;
  852. }
  853. fn div_mod_floor(&self, other: &BigUint) -> (BigUint, BigUint) {
  854. if other.is_zero() { panic!() }
  855. if self.is_zero() { return (Zero::zero(), Zero::zero()); }
  856. if *other == One::one() { return (self.clone(), Zero::zero()); }
  857. /* Required or the q_len calculation below can underflow: */
  858. match self.cmp(other) {
  859. Less => return (Zero::zero(), self.clone()),
  860. Equal => return (One::one(), Zero::zero()),
  861. Greater => {} // Do nothing
  862. }
  863. /*
  864. * This algorithm is from Knuth, TAOCP vol 2 section 4.3, algorithm D:
  865. *
  866. * First, normalize the arguments so the highest bit in the highest digit of the divisor is
  867. * set: the main loop uses the highest digit of the divisor for generating guesses, so we
  868. * want it to be the largest number we can efficiently divide by.
  869. */
  870. let shift = other.data.last().unwrap().leading_zeros() as usize;
  871. let mut a = self << shift;
  872. let b = other << shift;
  873. /*
  874. * The algorithm works by incrementally calculating "guesses", q0, for part of the
  875. * remainder. Once we have any number q0 such that q0 * b <= a, we can set
  876. *
  877. * q += q0
  878. * a -= q0 * b
  879. *
  880. * and then iterate until a < b. Then, (q, a) will be our desired quotient and remainder.
  881. *
  882. * q0, our guess, is calculated by dividing the last few digits of a by the last digit of b
  883. * - this should give us a guess that is "close" to the actual quotient, but is possibly
  884. * greater than the actual quotient. If q0 * b > a, we simply use iterated subtraction
  885. * until we have a guess such that q0 & b <= a.
  886. */
  887. let bn = *b.data.last().unwrap();
  888. let q_len = a.data.len() - b.data.len() + 1;
  889. let mut q = BigUint { data: vec![0; q_len] };
  890. /*
  891. * We reuse the same temporary to avoid hitting the allocator in our inner loop - this is
  892. * sized to hold a0 (in the common case; if a particular digit of the quotient is zero a0
  893. * can be bigger).
  894. */
  895. let mut tmp = BigUint { data: Vec::with_capacity(2) };
  896. for j in (0..q_len).rev() {
  897. /*
  898. * When calculating our next guess q0, we don't need to consider the digits below j
  899. * + b.data.len() - 1: we're guessing digit j of the quotient (i.e. q0 << j) from
  900. * digit bn of the divisor (i.e. bn << (b.data.len() - 1) - so the product of those
  901. * two numbers will be zero in all digits up to (j + b.data.len() - 1).
  902. */
  903. let offset = j + b.data.len() - 1;
  904. if offset >= a.data.len() {
  905. continue;
  906. }
  907. /* just avoiding a heap allocation: */
  908. let mut a0 = tmp;
  909. a0.data.truncate(0);
  910. a0.data.extend(a.data[offset..].iter().cloned());
  911. /*
  912. * q0 << j * big_digit::BITS is our actual quotient estimate - we do the shifts
  913. * implicitly at the end, when adding and subtracting to a and q. Not only do we
  914. * save the cost of the shifts, the rest of the arithmetic gets to work with
  915. * smaller numbers.
  916. */
  917. let (mut q0, _) = div_rem_digit(a0, bn);
  918. let mut prod = &b * &q0;
  919. while cmp_slice(&prod.data[..], &a.data[j..]) == Greater {
  920. let one: BigUint = One::one();
  921. q0 = q0 - one;
  922. prod = prod - &b;
  923. }
  924. add2(&mut q.data[j..], &q0.data[..]);
  925. sub2(&mut a.data[j..], &prod.data[..]);
  926. a = a.normalize();
  927. tmp = q0;
  928. }
  929. debug_assert!(a < b);
  930. (q.normalize(), a >> shift)
  931. }
  932. /// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
  933. ///
  934. /// The result is always positive.
  935. #[inline]
  936. fn gcd(&self, other: &BigUint) -> BigUint {
  937. // Use Euclid's algorithm
  938. let mut m = (*self).clone();
  939. let mut n = (*other).clone();
  940. while !m.is_zero() {
  941. let temp = m;
  942. m = n % &temp;
  943. n = temp;
  944. }
  945. return n;
  946. }
  947. /// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
  948. #[inline]
  949. fn lcm(&self, other: &BigUint) -> BigUint { ((self * other) / self.gcd(other)) }
  950. /// Deprecated, use `is_multiple_of` instead.
  951. #[inline]
  952. fn divides(&self, other: &BigUint) -> bool { self.is_multiple_of(other) }
  953. /// Returns `true` if the number is a multiple of `other`.
  954. #[inline]
  955. fn is_multiple_of(&self, other: &BigUint) -> bool { (self % other).is_zero() }
  956. /// Returns `true` if the number is divisible by `2`.
  957. #[inline]
  958. fn is_even(&self) -> bool {
  959. // Considering only the last digit.
  960. match self.data.first() {
  961. Some(x) => x.is_even(),
  962. None => true
  963. }
  964. }
  965. /// Returns `true` if the number is not divisible by `2`.
  966. #[inline]
  967. fn is_odd(&self) -> bool { !self.is_even() }
  968. }
  969. impl ToPrimitive for BigUint {
  970. #[inline]
  971. fn to_i64(&self) -> Option<i64> {
  972. self.to_u64().and_then(|n| {
  973. // If top bit of u64 is set, it's too large to convert to i64.
  974. if n >> 63 == 0 {
  975. Some(n as i64)
  976. } else {
  977. None
  978. }
  979. })
  980. }
  981. // `DoubleBigDigit` size dependent
  982. #[inline]
  983. fn to_u64(&self) -> Option<u64> {
  984. match self.data.len() {
  985. 0 => Some(0),
  986. 1 => Some(self.data[0] as u64),
  987. 2 => Some(big_digit::to_doublebigdigit(self.data[1], self.data[0])
  988. as u64),
  989. _ => None
  990. }
  991. }
  992. // `DoubleBigDigit` size dependent
  993. #[inline]
  994. fn to_f32(&self) -> Option<f32> {
  995. match self.data.len() {
  996. 0 => Some(f32::zero()),
  997. 1 => Some(self.data[0] as f32),
  998. len => {
  999. // prevent overflow of exponant
  1000. if len > (f32::MAX_EXP as usize) / big_digit::BITS {
  1001. None
  1002. } else {
  1003. let exponant = (len - 2) * big_digit::BITS;
  1004. // we need 25 significant digits, 24 to be stored and 1 for rounding
  1005. // this gives at least 33 significant digits
  1006. let mantissa = big_digit::to_doublebigdigit(self.data[len - 1], self.data[len - 2]);
  1007. // this cast handles rounding
  1008. let ret = (mantissa as f32) * 2.0.powi(exponant as i32);
  1009. if ret.is_infinite() {
  1010. None
  1011. } else {
  1012. Some(ret)
  1013. }
  1014. }
  1015. }
  1016. }
  1017. }
  1018. // `DoubleBigDigit` size dependent
  1019. #[inline]
  1020. fn to_f64(&self) -> Option<f64> {
  1021. match self.data.len() {
  1022. 0 => Some(f64::zero()),
  1023. 1 => Some(self.data[0] as f64),
  1024. 2 => Some(big_digit::to_doublebigdigit(self.data[1], self.data[0]) as f64),
  1025. len => {
  1026. // this will prevent any overflow of exponant
  1027. if len > (f64::MAX_EXP as usize) / big_digit::BITS {
  1028. None
  1029. } else {
  1030. let mut exponant = (len - 2) * big_digit::BITS;
  1031. let mut mantissa = big_digit::to_doublebigdigit(self.data[len - 1], self.data[len - 2]);
  1032. // we need at least 54 significant bit digits, 53 to be stored and 1 for rounding
  1033. // so we take enough from the next BigDigit to make it up if needed
  1034. let needed = (f64::MANTISSA_DIGITS as usize) + 1;
  1035. let bits = (2 * big_digit::BITS) - (mantissa.leading_zeros() as usize);
  1036. if needed > bits {
  1037. let diff = needed - bits;
  1038. mantissa <<= diff;
  1039. exponant -= diff;
  1040. let mut x = self.data[len - 3];
  1041. x >>= big_digit::BITS - diff;
  1042. mantissa |= x as u64;
  1043. }
  1044. // this cast handles rounding
  1045. let ret = (mantissa as f64) * 2.0.powi(exponant as i32);
  1046. if ret.is_infinite() {
  1047. None
  1048. } else {
  1049. Some(ret)
  1050. }
  1051. }
  1052. }
  1053. }
  1054. }
  1055. }
  1056. impl FromPrimitive for BigUint {
  1057. #[inline]
  1058. fn from_i64(n: i64) -> Option<BigUint> {
  1059. if n >= 0 {
  1060. Some(BigUint::from(n as u64))
  1061. } else {
  1062. None
  1063. }
  1064. }
  1065. #[inline]
  1066. fn from_u64(n: u64) -> Option<BigUint> {
  1067. Some(BigUint::from(n))
  1068. }
  1069. #[inline]
  1070. fn from_f32(n: f32) -> Option<BigUint> {
  1071. BigUint::from_f64(n as f64)
  1072. }
  1073. #[inline]
  1074. fn from_f64(mut n: f64) -> Option<BigUint> {
  1075. // handle NAN, INFINITY, NEG_INFINITY
  1076. if !n.is_finite() {
  1077. return None;
  1078. }
  1079. // match the rounding of casting from float to int
  1080. n = n.trunc();
  1081. // handle 0.x, -0.x
  1082. if n.is_zero() {
  1083. return Some(BigUint::zero());
  1084. }
  1085. let (mantissa, exponent, sign) = Float::integer_decode(n);
  1086. if sign == -1 {
  1087. return None;
  1088. }
  1089. let mut ret = BigUint::from(mantissa);
  1090. if exponent > 0 {
  1091. ret = ret << exponent as usize;
  1092. } else if exponent < 0 {
  1093. ret = ret >> (-exponent) as usize;
  1094. }
  1095. Some(ret)
  1096. }
  1097. }
  1098. impl From<u64> for BigUint {
  1099. // `DoubleBigDigit` size dependent
  1100. #[inline]
  1101. fn from(n: u64) -> Self {
  1102. match big_digit::from_doublebigdigit(n) {
  1103. (0, 0) => BigUint::zero(),
  1104. (0, n0) => BigUint { data: vec![n0] },
  1105. (n1, n0) => BigUint { data: vec![n0, n1] },
  1106. }
  1107. }
  1108. }
  1109. macro_rules! impl_biguint_from_uint {
  1110. ($T:ty) => {
  1111. impl From<$T> for BigUint {
  1112. #[inline]
  1113. fn from(n: $T) -> Self {
  1114. BigUint::from(n as u64)
  1115. }
  1116. }
  1117. }
  1118. }
  1119. impl_biguint_from_uint!(u8);
  1120. impl_biguint_from_uint!(u16);
  1121. impl_biguint_from_uint!(u32);
  1122. impl_biguint_from_uint!(usize);
  1123. /// A generic trait for converting a value to a `BigUint`.
  1124. pub trait ToBigUint {
  1125. /// Converts the value of `self` to a `BigUint`.
  1126. fn to_biguint(&self) -> Option<BigUint>;
  1127. }
  1128. impl ToBigUint for BigInt {
  1129. #[inline]
  1130. fn to_biguint(&self) -> Option<BigUint> {
  1131. if self.sign == Plus {
  1132. Some(self.data.clone())
  1133. } else if self.sign == NoSign {
  1134. Some(Zero::zero())
  1135. } else {
  1136. None
  1137. }
  1138. }
  1139. }
  1140. impl ToBigUint for BigUint {
  1141. #[inline]
  1142. fn to_biguint(&self) -> Option<BigUint> {
  1143. Some(self.clone())
  1144. }
  1145. }
  1146. macro_rules! impl_to_biguint {
  1147. ($T:ty, $from_ty:path) => {
  1148. impl ToBigUint for $T {
  1149. #[inline]
  1150. fn to_biguint(&self) -> Option<BigUint> {
  1151. $from_ty(*self)
  1152. }
  1153. }
  1154. }
  1155. }
  1156. impl_to_biguint!(isize, FromPrimitive::from_isize);
  1157. impl_to_biguint!(i8, FromPrimitive::from_i8);
  1158. impl_to_biguint!(i16, FromPrimitive::from_i16);
  1159. impl_to_biguint!(i32, FromPrimitive::from_i32);
  1160. impl_to_biguint!(i64, FromPrimitive::from_i64);
  1161. impl_to_biguint!(usize, FromPrimitive::from_usize);
  1162. impl_to_biguint!(u8, FromPrimitive::from_u8);
  1163. impl_to_biguint!(u16, FromPrimitive::from_u16);
  1164. impl_to_biguint!(u32, FromPrimitive::from_u32);
  1165. impl_to_biguint!(u64, FromPrimitive::from_u64);
  1166. impl_to_biguint!(f32, FromPrimitive::from_f32);
  1167. impl_to_biguint!(f64, FromPrimitive::from_f64);
  1168. // Extract bitwise digits that evenly divide BigDigit
  1169. fn to_bitwise_digits_le(u: &BigUint, bits: usize) -> Vec<u8> {
  1170. debug_assert!(!u.is_zero() && bits <= 8 && big_digit::BITS % bits == 0);
  1171. let last_i = u.data.len() - 1;
  1172. let mask: BigDigit = (1 << bits) - 1;
  1173. let digits_per_big_digit = big_digit::BITS / bits;
  1174. let digits = (u.bits() + bits - 1) / bits;
  1175. let mut res = Vec::with_capacity(digits);
  1176. for mut r in u.data[..last_i].iter().cloned() {
  1177. for _ in 0..digits_per_big_digit {
  1178. res.push((r & mask) as u8);
  1179. r >>= bits;
  1180. }
  1181. }
  1182. let mut r = u.data[last_i];
  1183. while r != 0 {
  1184. res.push((r & mask) as u8);
  1185. r >>= bits;
  1186. }
  1187. res
  1188. }
  1189. // Extract bitwise digits that don't evenly divide BigDigit
  1190. fn to_inexact_bitwise_digits_le(u: &BigUint, bits: usize) -> Vec<u8> {
  1191. debug_assert!(!u.is_zero() && bits <= 8 && big_digit::BITS % bits != 0);
  1192. let last_i = u.data.len() - 1;
  1193. let mask: DoubleBigDigit = (1 << bits) - 1;
  1194. let digits = (u.bits() + bits - 1) / bits;
  1195. let mut res = Vec::with_capacity(digits);
  1196. let mut r = 0;
  1197. let mut rbits = 0;
  1198. for hi in u.data[..last_i].iter().cloned() {
  1199. r |= (hi as DoubleBigDigit) << rbits;
  1200. rbits += big_digit::BITS;
  1201. while rbits >= bits {
  1202. res.push((r & mask) as u8);
  1203. r >>= bits;
  1204. rbits -= bits;
  1205. }
  1206. }
  1207. r |= (u.data[last_i] as DoubleBigDigit) << rbits;
  1208. while r != 0 {
  1209. res.push((r & mask) as u8);
  1210. r >>= bits;
  1211. }
  1212. res
  1213. }
  1214. // Extract little-endian radix digits
  1215. #[inline(always)] // forced inline to get const-prop for radix=10
  1216. fn to_radix_digits_le(u: &BigUint, radix: u32) -> Vec<u8> {
  1217. debug_assert!(!u.is_zero() && !radix.is_power_of_two());
  1218. // Estimate how big the result will be, so we can pre-allocate it.
  1219. let radix_digits = ((u.bits() as f64) / (radix as f64).log2()).ceil();
  1220. let mut res = Vec::with_capacity(radix_digits as usize);
  1221. let mut digits = u.clone();
  1222. let (base, power) = get_radix_base(radix);
  1223. debug_assert!(base < (1 << 32));
  1224. let base = base as BigDigit;
  1225. while digits.data.len() > 1 {
  1226. let (q, mut r) = div_rem_digit(digits, base);
  1227. for _ in 0..power {
  1228. res.push((r % radix) as u8);
  1229. r /= radix;
  1230. }
  1231. digits = q;
  1232. }
  1233. let mut r = digits.data[0];
  1234. while r != 0 {
  1235. res.push((r % radix) as u8);
  1236. r /= radix;
  1237. }
  1238. res
  1239. }
  1240. fn to_str_radix_reversed(u: &BigUint, radix: u32) -> Vec<u8> {
  1241. assert!(2 <= radix && radix <= 36, "The radix must be within 2...36");
  1242. if u.is_zero() {
  1243. return vec![b'0']
  1244. }
  1245. let mut res = if radix.is_power_of_two() {
  1246. // Powers of two can use bitwise masks and shifting instead of division
  1247. let bits = radix.trailing_zeros() as usize;
  1248. if big_digit::BITS % bits == 0 {
  1249. to_bitwise_digits_le(u, bits)
  1250. } else {
  1251. to_inexact_bitwise_digits_le(u, bits)
  1252. }
  1253. } else if radix == 10 {
  1254. // 10 is so common that it's worth separating out for const-propagation.
  1255. // Optimizers can often turn constant division into a faster multiplication.
  1256. to_radix_digits_le(u, 10)
  1257. } else {
  1258. to_radix_digits_le(u, radix)
  1259. };
  1260. // Now convert everything to ASCII digits.
  1261. for r in &mut res {
  1262. const DIGITS: &'static [u8; 36] = b"0123456789abcdefghijklmnopqrstuvwxyz";
  1263. *r = DIGITS[*r as usize];
  1264. }
  1265. res
  1266. }
  1267. impl BigUint {
  1268. /// Creates and initializes a `BigUint`.
  1269. ///
  1270. /// The digits are in little-endian base 2^32.
  1271. #[inline]
  1272. pub fn new(digits: Vec<BigDigit>) -> BigUint {
  1273. BigUint { data: digits }.normalize()
  1274. }
  1275. /// Creates and initializes a `BigUint`.
  1276. ///
  1277. /// The digits are in little-endian base 2^32.
  1278. #[inline]
  1279. pub fn from_slice(slice: &[BigDigit]) -> BigUint {
  1280. BigUint::new(slice.to_vec())
  1281. }
  1282. /// Creates and initializes a `BigUint`.
  1283. ///
  1284. /// The bytes are in big-endian byte order.
  1285. ///
  1286. /// # Examples
  1287. ///
  1288. /// ```
  1289. /// use num::bigint::BigUint;
  1290. ///
  1291. /// assert_eq!(BigUint::from_bytes_be(b"A"),
  1292. /// BigUint::parse_bytes(b"65", 10).unwrap());
  1293. /// assert_eq!(BigUint::from_bytes_be(b"AA"),
  1294. /// BigUint::parse_bytes(b"16705", 10).unwrap());
  1295. /// assert_eq!(BigUint::from_bytes_be(b"AB"),
  1296. /// BigUint::parse_bytes(b"16706", 10).unwrap());
  1297. /// assert_eq!(BigUint::from_bytes_be(b"Hello world!"),
  1298. /// BigUint::parse_bytes(b"22405534230753963835153736737", 10).unwrap());
  1299. /// ```
  1300. #[inline]
  1301. pub fn from_bytes_be(bytes: &[u8]) -> BigUint {
  1302. if bytes.is_empty() {
  1303. Zero::zero()
  1304. } else {
  1305. let mut v = bytes.to_vec();
  1306. v.reverse();
  1307. BigUint::from_bytes_le(&*v)
  1308. }
  1309. }
  1310. /// Creates and initializes a `BigUint`.
  1311. ///
  1312. /// The bytes are in little-endian byte order.
  1313. #[inline]
  1314. pub fn from_bytes_le(bytes: &[u8]) -> BigUint {
  1315. if bytes.is_empty() {
  1316. Zero::zero()
  1317. } else {
  1318. from_bitwise_digits_le(bytes, 8)
  1319. }
  1320. }
  1321. /// Returns the byte representation of the `BigUint` in little-endian byte order.
  1322. ///
  1323. /// # Examples
  1324. ///
  1325. /// ```
  1326. /// use num::bigint::BigUint;
  1327. ///
  1328. /// let i = BigUint::parse_bytes(b"1125", 10).unwrap();
  1329. /// assert_eq!(i.to_bytes_le(), vec![101, 4]);
  1330. /// ```
  1331. #[inline]
  1332. pub fn to_bytes_le(&self) -> Vec<u8> {
  1333. if self.is_zero() {
  1334. vec![0]
  1335. } else {
  1336. to_bitwise_digits_le(self, 8)
  1337. }
  1338. }
  1339. /// Returns the byte representation of the `BigUint` in big-endian byte order.
  1340. ///
  1341. /// # Examples
  1342. ///
  1343. /// ```
  1344. /// use num::bigint::BigUint;
  1345. ///
  1346. /// let i = BigUint::parse_bytes(b"1125", 10).unwrap();
  1347. /// assert_eq!(i.to_bytes_be(), vec![4, 101]);
  1348. /// ```
  1349. #[inline]
  1350. pub fn to_bytes_be(&self) -> Vec<u8> {
  1351. let mut v = self.to_bytes_le();
  1352. v.reverse();
  1353. v
  1354. }
  1355. /// Returns the integer formatted as a string in the given radix.
  1356. /// `radix` must be in the range `[2, 36]`.
  1357. ///
  1358. /// # Examples
  1359. ///
  1360. /// ```
  1361. /// use num::bigint::BigUint;
  1362. ///
  1363. /// let i = BigUint::parse_bytes(b"ff", 16).unwrap();
  1364. /// assert_eq!(i.to_str_radix(16), "ff");
  1365. /// ```
  1366. #[inline]
  1367. pub fn to_str_radix(&self, radix: u32) -> String {
  1368. let mut v = to_str_radix_reversed(self, radix);
  1369. v.reverse();
  1370. unsafe { String::from_utf8_unchecked(v) }
  1371. }
  1372. /// Creates and initializes a `BigUint`.
  1373. ///
  1374. /// # Examples
  1375. ///
  1376. /// ```
  1377. /// use num::bigint::{BigUint, ToBigUint};
  1378. ///
  1379. /// assert_eq!(BigUint::parse_bytes(b"1234", 10), ToBigUint::to_biguint(&1234));
  1380. /// assert_eq!(BigUint::parse_bytes(b"ABCD", 16), ToBigUint::to_biguint(&0xABCD));
  1381. /// assert_eq!(BigUint::parse_bytes(b"G", 16), None);
  1382. /// ```
  1383. #[inline]
  1384. pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigUint> {
  1385. str::from_utf8(buf).ok().and_then(|s| BigUint::from_str_radix(s, radix).ok())
  1386. }
  1387. #[inline]
  1388. fn shl_unit(&self, n_unit: usize) -> BigUint {
  1389. if n_unit == 0 || self.is_zero() { return self.clone(); }
  1390. let mut v = vec![0; n_unit];
  1391. v.extend(self.data.iter().cloned());
  1392. BigUint::new(v)
  1393. }
  1394. #[inline]
  1395. fn shl_bits(self, n_bits: usize) -> BigUint {
  1396. if n_bits == 0 || self.is_zero() { return self; }
  1397. assert!(n_bits < big_digit::BITS);
  1398. let mut carry = 0;
  1399. let mut shifted = self.data;
  1400. for elem in shifted.iter_mut() {
  1401. let new_carry = *elem >> (big_digit::BITS - n_bits);
  1402. *elem = (*elem << n_bits) | carry;
  1403. carry = new_carry;
  1404. }
  1405. if carry != 0 {
  1406. shifted.push(carry);
  1407. }
  1408. BigUint::new(shifted)
  1409. }
  1410. #[inline]
  1411. fn shr_unit(&self, n_unit: usize) -> BigUint {
  1412. if n_unit == 0 { return self.clone(); }
  1413. if self.data.len() < n_unit { return Zero::zero(); }
  1414. BigUint::from_slice(&self.data[n_unit ..])
  1415. }
  1416. #[inline]
  1417. fn shr_bits(self, n_bits: usize) -> BigUint {
  1418. if n_bits == 0 || self.data.is_empty() { return self; }
  1419. assert!(n_bits < big_digit::BITS);
  1420. let mut borrow = 0;
  1421. let mut shifted = self.data;
  1422. for elem in shifted.iter_mut().rev() {
  1423. let new_borrow = *elem << (big_digit::BITS - n_bits);
  1424. *elem = (*elem >> n_bits) | borrow;
  1425. borrow = new_borrow;
  1426. }
  1427. BigUint::new(shifted)
  1428. }
  1429. /// Determines the fewest bits necessary to express the `BigUint`.
  1430. pub fn bits(&self) -> usize {
  1431. if self.is_zero() { return 0; }
  1432. let zeros = self.data.last().unwrap().leading_zeros();
  1433. return self.data.len()*big_digit::BITS - zeros as usize;
  1434. }
  1435. /// Strips off trailing zero bigdigits - comparisons require the last element in the vector to
  1436. /// be nonzero.
  1437. #[inline]
  1438. fn normalize(mut self) -> BigUint {
  1439. while let Some(&0) = self.data.last() {
  1440. self.data.pop();
  1441. }
  1442. self
  1443. }
  1444. }
  1445. // `DoubleBigDigit` size dependent
  1446. /// Returns the greatest power of the radix <= big_digit::BASE
  1447. #[inline]
  1448. fn get_radix_base(radix: u32) -> (DoubleBigDigit, usize) {
  1449. // To generate this table:
  1450. // let target = std::u32::max as u64 + 1;
  1451. // for radix in 2u64..37 {
  1452. // let power = (target as f64).log(radix as f64) as u32;
  1453. // let base = radix.pow(power);
  1454. // println!("({:10}, {:2}), // {:2}", base, power, radix);
  1455. // }
  1456. const BASES: [(DoubleBigDigit, usize); 37] = [
  1457. (0, 0), (0, 0),
  1458. (4294967296, 32), // 2
  1459. (3486784401, 20), // 3
  1460. (4294967296, 16), // 4
  1461. (1220703125, 13), // 5
  1462. (2176782336, 12), // 6
  1463. (1977326743, 11), // 7
  1464. (1073741824, 10), // 8
  1465. (3486784401, 10), // 9
  1466. (1000000000, 9), // 10
  1467. (2357947691, 9), // 11
  1468. ( 429981696, 8), // 12
  1469. ( 815730721, 8), // 13
  1470. (1475789056, 8), // 14
  1471. (2562890625, 8), // 15
  1472. (4294967296, 8), // 16
  1473. ( 410338673, 7), // 17
  1474. ( 612220032, 7), // 18
  1475. ( 893871739, 7), // 19
  1476. (1280000000, 7), // 20
  1477. (1801088541, 7), // 21
  1478. (2494357888, 7), // 22
  1479. (3404825447, 7), // 23
  1480. ( 191102976, 6), // 24
  1481. ( 244140625, 6), // 25
  1482. ( 308915776, 6), // 26
  1483. ( 387420489, 6), // 27
  1484. ( 481890304, 6), // 28
  1485. ( 594823321, 6), // 29
  1486. ( 729000000, 6), // 30
  1487. ( 887503681, 6), // 31
  1488. (1073741824, 6), // 32
  1489. (1291467969, 6), // 33
  1490. (1544804416, 6), // 34
  1491. (1838265625, 6), // 35
  1492. (2176782336, 6), // 36
  1493. ];
  1494. assert!(2 <= radix && radix <= 36, "The radix must be within 2...36");
  1495. BASES[radix as usize]
  1496. }
  1497. /// A Sign is a `BigInt`'s composing element.
  1498. #[derive(PartialEq, PartialOrd, Eq, Ord, Copy, Clone, Debug, RustcEncodable, RustcDecodable, Hash)]
  1499. pub enum Sign { Minus, NoSign, Plus }
  1500. impl Neg for Sign {
  1501. type Output = Sign;
  1502. /// Negate Sign value.
  1503. #[inline]
  1504. fn neg(self) -> Sign {
  1505. match self {
  1506. Minus => Plus,
  1507. NoSign => NoSign,
  1508. Plus => Minus
  1509. }
  1510. }
  1511. }
  1512. impl Mul<Sign> for Sign {
  1513. type Output = Sign;
  1514. #[inline]
  1515. fn mul(self, other: Sign) -> Sign {
  1516. match (self, other) {
  1517. (NoSign, _) | (_, NoSign) => NoSign,
  1518. (Plus, Plus) | (Minus, Minus) => Plus,
  1519. (Plus, Minus) | (Minus, Plus) => Minus,
  1520. }
  1521. }
  1522. }
  1523. /// A big signed integer type.
  1524. #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash)]
  1525. pub struct BigInt {
  1526. sign: Sign,
  1527. data: BigUint
  1528. }
  1529. impl PartialEq for BigInt {
  1530. #[inline]
  1531. fn eq(&self, other: &BigInt) -> bool {
  1532. self.cmp(other) == Equal
  1533. }
  1534. }
  1535. impl Eq for BigInt {}
  1536. impl PartialOrd for BigInt {
  1537. #[inline]
  1538. fn partial_cmp(&self, other: &BigInt) -> Option<Ordering> {
  1539. Some(self.cmp(other))
  1540. }
  1541. }
  1542. impl Ord for BigInt {
  1543. #[inline]
  1544. fn cmp(&self, other: &BigInt) -> Ordering {
  1545. let scmp = self.sign.cmp(&other.sign);
  1546. if scmp != Equal { return scmp; }
  1547. match self.sign {
  1548. NoSign => Equal,
  1549. Plus => self.data.cmp(&other.data),
  1550. Minus => other.data.cmp(&self.data),
  1551. }
  1552. }
  1553. }
  1554. impl Default for BigInt {
  1555. #[inline]
  1556. fn default() -> BigInt { Zero::zero() }
  1557. }
  1558. impl fmt::Display for BigInt {
  1559. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  1560. write!(f, "{}", self.to_str_radix(10))
  1561. }
  1562. }
  1563. impl FromStr for BigInt {
  1564. type Err = ParseBigIntError;
  1565. #[inline]
  1566. fn from_str(s: &str) -> Result<BigInt, ParseBigIntError> {
  1567. BigInt::from_str_radix(s, 10)
  1568. }
  1569. }
  1570. impl Num for BigInt {
  1571. type FromStrRadixErr = ParseBigIntError;
  1572. /// Creates and initializes a BigInt.
  1573. #[inline]
  1574. fn from_str_radix(mut s: &str, radix: u32) -> Result<BigInt, ParseBigIntError> {
  1575. let sign = if s.starts_with('-') { s = &s[1..]; Minus } else { Plus };
  1576. let bu = try!(BigUint::from_str_radix(s, radix));
  1577. Ok(BigInt::from_biguint(sign, bu))
  1578. }
  1579. }
  1580. impl Shl<usize> for BigInt {
  1581. type Output = BigInt;
  1582. #[inline]
  1583. fn shl(self, rhs: usize) -> BigInt { (&self) << rhs }
  1584. }
  1585. impl<'a> Shl<usize> for &'a BigInt {
  1586. type Output = BigInt;
  1587. #[inline]
  1588. fn shl(self, rhs: usize) -> BigInt {
  1589. BigInt::from_biguint(self.sign, &self.data << rhs)
  1590. }
  1591. }
  1592. impl Shr<usize> for BigInt {
  1593. type Output = BigInt;
  1594. #[inline]
  1595. fn shr(self, rhs: usize) -> BigInt { (&self) >> rhs }
  1596. }
  1597. impl<'a> Shr<usize> for &'a BigInt {
  1598. type Output = BigInt;
  1599. #[inline]
  1600. fn shr(self, rhs: usize) -> BigInt {
  1601. BigInt::from_biguint(self.sign, &self.data >> rhs)
  1602. }
  1603. }
  1604. impl Zero for BigInt {
  1605. #[inline]
  1606. fn zero() -> BigInt {
  1607. BigInt::from_biguint(NoSign, Zero::zero())
  1608. }
  1609. #[inline]
  1610. fn is_zero(&self) -> bool { self.sign == NoSign }
  1611. }
  1612. impl One for BigInt {
  1613. #[inline]
  1614. fn one() -> BigInt {
  1615. BigInt::from_biguint(Plus, One::one())
  1616. }
  1617. }
  1618. impl Signed for BigInt {
  1619. #[inline]
  1620. fn abs(&self) -> BigInt {
  1621. match self.sign {
  1622. Plus | NoSign => self.clone(),
  1623. Minus => BigInt::from_biguint(Plus, self.data.clone())
  1624. }
  1625. }
  1626. #[inline]
  1627. fn abs_sub(&self, other: &BigInt) -> BigInt {
  1628. if *self <= *other { Zero::zero() } else { self - other }
  1629. }
  1630. #[inline]
  1631. fn signum(&self) -> BigInt {
  1632. match self.sign {
  1633. Plus => BigInt::from_biguint(Plus, One::one()),
  1634. Minus => BigInt::from_biguint(Minus, One::one()),
  1635. NoSign => Zero::zero(),
  1636. }
  1637. }
  1638. #[inline]
  1639. fn is_positive(&self) -> bool { self.sign == Plus }
  1640. #[inline]
  1641. fn is_negative(&self) -> bool { self.sign == Minus }
  1642. }
  1643. // We want to forward to BigUint::add, but it's not clear how that will go until
  1644. // we compare both sign and magnitude. So we duplicate this body for every
  1645. // val/ref combination, deferring that decision to BigUint's own forwarding.
  1646. macro_rules! bigint_add {
  1647. ($a:expr, $a_owned:expr, $a_data:expr, $b:expr, $b_owned:expr, $b_data:expr) => {
  1648. match ($a.sign, $b.sign) {
  1649. (_, NoSign) => $a_owned,
  1650. (NoSign, _) => $b_owned,
  1651. // same sign => keep the sign with the sum of magnitudes
  1652. (Plus, Plus) | (Minus, Minus) =>
  1653. BigInt::from_biguint($a.sign, $a_data + $b_data),
  1654. // opposite signs => keep the sign of the larger with the difference of magnitudes
  1655. (Plus, Minus) | (Minus, Plus) =>
  1656. match $a.data.cmp(&$b.data) {
  1657. Less => BigInt::from_biguint($b.sign, $b_data - $a_data),
  1658. Greater => BigInt::from_biguint($a.sign, $a_data - $b_data),
  1659. Equal => Zero::zero(),
  1660. },
  1661. }
  1662. };
  1663. }
  1664. impl<'a, 'b> Add<&'b BigInt> for &'a BigInt {
  1665. type Output = BigInt;
  1666. #[inline]
  1667. fn add(self, other: &BigInt) -> BigInt {
  1668. bigint_add!(self, self.clone(), &self.data, other, other.clone(), &other.data)
  1669. }
  1670. }
  1671. impl<'a> Add<BigInt> for &'a BigInt {
  1672. type Output = BigInt;
  1673. #[inline]
  1674. fn add(self, other: BigInt) -> BigInt {
  1675. bigint_add!(self, self.clone(), &self.data, other, other, other.data)
  1676. }
  1677. }
  1678. impl<'a> Add<&'a BigInt> for BigInt {
  1679. type Output = BigInt;
  1680. #[inline]
  1681. fn add(self, other: &BigInt) -> BigInt {
  1682. bigint_add!(self, self, self.data, other, other.clone(), &other.data)
  1683. }
  1684. }
  1685. impl Add<BigInt> for BigInt {
  1686. type Output = BigInt;
  1687. #[inline]
  1688. fn add(self, other: BigInt) -> BigInt {
  1689. bigint_add!(self, self, self.data, other, other, other.data)
  1690. }
  1691. }
  1692. // We want to forward to BigUint::sub, but it's not clear how that will go until
  1693. // we compare both sign and magnitude. So we duplicate this body for every
  1694. // val/ref combination, deferring that decision to BigUint's own forwarding.
  1695. macro_rules! bigint_sub {
  1696. ($a:expr, $a_owned:expr, $a_data:expr, $b:expr, $b_owned:expr, $b_data:expr) => {
  1697. match ($a.sign, $b.sign) {
  1698. (_, NoSign) => $a_owned,
  1699. (NoSign, _) => -$b_owned,
  1700. // opposite signs => keep the sign of the left with the sum of magnitudes
  1701. (Plus, Minus) | (Minus, Plus) =>
  1702. BigInt::from_biguint($a.sign, $a_data + $b_data),
  1703. // same sign => keep or toggle the sign of the left with the difference of magnitudes
  1704. (Plus, Plus) | (Minus, Minus) =>
  1705. match $a.data.cmp(&$b.data) {
  1706. Less => BigInt::from_biguint(-$a.sign, $b_data - $a_data),
  1707. Greater => BigInt::from_biguint($a.sign, $a_data - $b_data),
  1708. Equal => Zero::zero(),
  1709. },
  1710. }
  1711. };
  1712. }
  1713. impl<'a, 'b> Sub<&'b BigInt> for &'a BigInt {
  1714. type Output = BigInt;
  1715. #[inline]
  1716. fn sub(self, other: &BigInt) -> BigInt {
  1717. bigint_sub!(self, self.clone(), &self.data, other, other.clone(), &other.data)
  1718. }
  1719. }
  1720. impl<'a> Sub<BigInt> for &'a BigInt {
  1721. type Output = BigInt;
  1722. #[inline]
  1723. fn sub(self, other: BigInt) -> BigInt {
  1724. bigint_sub!(self, self.clone(), &self.data, other, other, other.data)
  1725. }
  1726. }
  1727. impl<'a> Sub<&'a BigInt> for BigInt {
  1728. type Output = BigInt;
  1729. #[inline]
  1730. fn sub(self, other: &BigInt) -> BigInt {
  1731. bigint_sub!(self, self, self.data, other, other.clone(), &other.data)
  1732. }
  1733. }
  1734. impl Sub<BigInt> for BigInt {
  1735. type Output = BigInt;
  1736. #[inline]
  1737. fn sub(self, other: BigInt) -> BigInt {
  1738. bigint_sub!(self, self, self.data, other, other, other.data)
  1739. }
  1740. }
  1741. forward_all_binop_to_ref_ref!(impl Mul for BigInt, mul);
  1742. impl<'a, 'b> Mul<&'b BigInt> for &'a BigInt {
  1743. type Output = BigInt;
  1744. #[inline]
  1745. fn mul(self, other: &BigInt) -> BigInt {
  1746. BigInt::from_biguint(self.sign * other.sign,
  1747. &self.data * &other.data)
  1748. }
  1749. }
  1750. forward_all_binop_to_ref_ref!(impl Div for BigInt, div);
  1751. impl<'a, 'b> Div<&'b BigInt> for &'a BigInt {
  1752. type Output = BigInt;
  1753. #[inline]
  1754. fn div(self, other: &BigInt) -> BigInt {
  1755. let (q, _) = self.div_rem(other);
  1756. q
  1757. }
  1758. }
  1759. forward_all_binop_to_ref_ref!(impl Rem for BigInt, rem);
  1760. impl<'a, 'b> Rem<&'b BigInt> for &'a BigInt {
  1761. type Output = BigInt;
  1762. #[inline]
  1763. fn rem(self, other: &BigInt) -> BigInt {
  1764. let (_, r) = self.div_rem(other);
  1765. r
  1766. }
  1767. }
  1768. impl Neg for BigInt {
  1769. type Output = BigInt;
  1770. #[inline]
  1771. fn neg(mut self) -> BigInt {
  1772. self.sign = -self.sign;
  1773. self
  1774. }
  1775. }
  1776. impl<'a> Neg for &'a BigInt {
  1777. type Output = BigInt;
  1778. #[inline]
  1779. fn neg(self) -> BigInt {
  1780. -self.clone()
  1781. }
  1782. }
  1783. impl CheckedAdd for BigInt {
  1784. #[inline]
  1785. fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
  1786. return Some(self.add(v));
  1787. }
  1788. }
  1789. impl CheckedSub for BigInt {
  1790. #[inline]
  1791. fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
  1792. return Some(self.sub(v));
  1793. }
  1794. }
  1795. impl CheckedMul for BigInt {
  1796. #[inline]
  1797. fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
  1798. return Some(self.mul(v));
  1799. }
  1800. }
  1801. impl CheckedDiv for BigInt {
  1802. #[inline]
  1803. fn checked_div(&self, v: &BigInt) -> Option<BigInt> {
  1804. if v.is_zero() {
  1805. return None;
  1806. }
  1807. return Some(self.div(v));
  1808. }
  1809. }
  1810. impl Integer for BigInt {
  1811. #[inline]
  1812. fn div_rem(&self, other: &BigInt) -> (BigInt, BigInt) {
  1813. // r.sign == self.sign
  1814. let (d_ui, r_ui) = self.data.div_mod_floor(&other.data);
  1815. let d = BigInt::from_biguint(self.sign, d_ui);
  1816. let r = BigInt::from_biguint(self.sign, r_ui);
  1817. if other.is_negative() { (-d, r) } else { (d, r) }
  1818. }
  1819. #[inline]
  1820. fn div_floor(&self, other: &BigInt) -> BigInt {
  1821. let (d, _) = self.div_mod_floor(other);
  1822. d
  1823. }
  1824. #[inline]
  1825. fn mod_floor(&self, other: &BigInt) -> BigInt {
  1826. let (_, m) = self.div_mod_floor(other);
  1827. m
  1828. }
  1829. fn div_mod_floor(&self, other: &BigInt) -> (BigInt, BigInt) {
  1830. // m.sign == other.sign
  1831. let (d_ui, m_ui) = self.data.div_rem(&other.data);
  1832. let d = BigInt::from_biguint(Plus, d_ui);
  1833. let m = BigInt::from_biguint(Plus, m_ui);
  1834. let one: BigInt = One::one();
  1835. match (self.sign, other.sign) {
  1836. (_, NoSign) => panic!(),
  1837. (Plus, Plus) | (NoSign, Plus) => (d, m),
  1838. (Plus, Minus) | (NoSign, Minus) => {
  1839. if m.is_zero() {
  1840. (-d, Zero::zero())
  1841. } else {
  1842. (-d - one, m + other)
  1843. }
  1844. },
  1845. (Minus, Plus) => {
  1846. if m.is_zero() {
  1847. (-d, Zero::zero())
  1848. } else {
  1849. (-d - one, other - m)
  1850. }
  1851. }
  1852. (Minus, Minus) => (d, -m)
  1853. }
  1854. }
  1855. /// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
  1856. ///
  1857. /// The result is always positive.
  1858. #[inline]
  1859. fn gcd(&self, other: &BigInt) -> BigInt {
  1860. BigInt::from_biguint(Plus, self.data.gcd(&other.data))
  1861. }
  1862. /// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
  1863. #[inline]
  1864. fn lcm(&self, other: &BigInt) -> BigInt {
  1865. BigInt::from_biguint(Plus, self.data.lcm(&other.data))
  1866. }
  1867. /// Deprecated, use `is_multiple_of` instead.
  1868. #[inline]
  1869. fn divides(&self, other: &BigInt) -> bool { return self.is_multiple_of(other); }
  1870. /// Returns `true` if the number is a multiple of `other`.
  1871. #[inline]
  1872. fn is_multiple_of(&self, other: &BigInt) -> bool { self.data.is_multiple_of(&other.data) }
  1873. /// Returns `true` if the number is divisible by `2`.
  1874. #[inline]
  1875. fn is_even(&self) -> bool { self.data.is_even() }
  1876. /// Returns `true` if the number is not divisible by `2`.
  1877. #[inline]
  1878. fn is_odd(&self) -> bool { self.data.is_odd() }
  1879. }
  1880. impl ToPrimitive for BigInt {
  1881. #[inline]
  1882. fn to_i64(&self) -> Option<i64> {
  1883. match self.sign {
  1884. Plus => self.data.to_i64(),
  1885. NoSign => Some(0),
  1886. Minus => {
  1887. self.data.to_u64().and_then(|n| {
  1888. let m: u64 = 1 << 63;
  1889. if n < m {
  1890. Some(-(n as i64))
  1891. } else if n == m {
  1892. Some(i64::MIN)
  1893. } else {
  1894. None
  1895. }
  1896. })
  1897. }
  1898. }
  1899. }
  1900. #[inline]
  1901. fn to_u64(&self) -> Option<u64> {
  1902. match self.sign {
  1903. Plus => self.data.to_u64(),
  1904. NoSign => Some(0),
  1905. Minus => None
  1906. }
  1907. }
  1908. #[inline]
  1909. fn to_f32(&self) -> Option<f32> {
  1910. self.data.to_f32().map(|n| if self.sign == Minus { -n } else { n })
  1911. }
  1912. #[inline]
  1913. fn to_f64(&self) -> Option<f64> {
  1914. self.data.to_f64().map(|n| if self.sign == Minus { -n } else { n })
  1915. }
  1916. }
  1917. impl FromPrimitive for BigInt {
  1918. #[inline]
  1919. fn from_i64(n: i64) -> Option<BigInt> {
  1920. Some(BigInt::from(n))
  1921. }
  1922. #[inline]
  1923. fn from_u64(n: u64) -> Option<BigInt> {
  1924. Some(BigInt::from(n))
  1925. }
  1926. #[inline]
  1927. fn from_f32(n: f32) -> Option<BigInt> {
  1928. if n >= 0.0 {
  1929. BigUint::from_f32(n).map(|x| BigInt::from_biguint(Plus, x))
  1930. } else {
  1931. BigUint::from_f32(-n).map(|x| BigInt::from_biguint(Minus, x))
  1932. }
  1933. }
  1934. #[inline]
  1935. fn from_f64(n: f64) -> Option<BigInt> {
  1936. if n >= 0.0 {
  1937. BigUint::from_f64(n).map(|x| BigInt::from_biguint(Plus, x))
  1938. } else {
  1939. BigUint::from_f64(-n).map(|x| BigInt::from_biguint(Minus, x))
  1940. }
  1941. }
  1942. }
  1943. impl From<i64> for BigInt {
  1944. #[inline]
  1945. fn from(n: i64) -> Self {
  1946. if n >= 0 {
  1947. BigInt::from(n as u64)
  1948. } else {
  1949. let u = u64::MAX - (n as u64) + 1;
  1950. BigInt { sign: Minus, data: BigUint::from(u) }
  1951. }
  1952. }
  1953. }
  1954. macro_rules! impl_bigint_from_int {
  1955. ($T:ty) => {
  1956. impl From<$T> for BigInt {
  1957. #[inline]
  1958. fn from(n: $T) -> Self {
  1959. BigInt::from(n as i64)
  1960. }
  1961. }
  1962. }
  1963. }
  1964. impl_bigint_from_int!(i8);
  1965. impl_bigint_from_int!(i16);
  1966. impl_bigint_from_int!(i32);
  1967. impl_bigint_from_int!(isize);
  1968. impl From<u64> for BigInt {
  1969. #[inline]
  1970. fn from(n: u64) -> Self {
  1971. if n > 0 {
  1972. BigInt { sign: Plus, data: BigUint::from(n) }
  1973. } else {
  1974. BigInt::zero()
  1975. }
  1976. }
  1977. }
  1978. macro_rules! impl_bigint_from_uint {
  1979. ($T:ty) => {
  1980. impl From<$T> for BigInt {
  1981. #[inline]
  1982. fn from(n: $T) -> Self {
  1983. BigInt::from(n as u64)
  1984. }
  1985. }
  1986. }
  1987. }
  1988. impl_bigint_from_uint!(u8);
  1989. impl_bigint_from_uint!(u16);
  1990. impl_bigint_from_uint!(u32);
  1991. impl_bigint_from_uint!(usize);
  1992. impl From<BigUint> for BigInt {
  1993. #[inline]
  1994. fn from(n: BigUint) -> Self {
  1995. if n.is_zero() {
  1996. BigInt::zero()
  1997. } else {
  1998. BigInt { sign: Plus, data: n }
  1999. }
  2000. }
  2001. }
  2002. /// A generic trait for converting a value to a `BigInt`.
  2003. pub trait ToBigInt {
  2004. /// Converts the value of `self` to a `BigInt`.
  2005. fn to_bigint(&self) -> Option<BigInt>;
  2006. }
  2007. impl ToBigInt for BigInt {
  2008. #[inline]
  2009. fn to_bigint(&self) -> Option<BigInt> {
  2010. Some(self.clone())
  2011. }
  2012. }
  2013. impl ToBigInt for BigUint {
  2014. #[inline]
  2015. fn to_bigint(&self) -> Option<BigInt> {
  2016. if self.is_zero() {
  2017. Some(Zero::zero())
  2018. } else {
  2019. Some(BigInt { sign: Plus, data: self.clone() })
  2020. }
  2021. }
  2022. }
  2023. macro_rules! impl_to_bigint {
  2024. ($T:ty, $from_ty:path) => {
  2025. impl ToBigInt for $T {
  2026. #[inline]
  2027. fn to_bigint(&self) -> Option<BigInt> {
  2028. $from_ty(*self)
  2029. }
  2030. }
  2031. }
  2032. }
  2033. impl_to_bigint!(isize, FromPrimitive::from_isize);
  2034. impl_to_bigint!(i8, FromPrimitive::from_i8);
  2035. impl_to_bigint!(i16, FromPrimitive::from_i16);
  2036. impl_to_bigint!(i32, FromPrimitive::from_i32);
  2037. impl_to_bigint!(i64, FromPrimitive::from_i64);
  2038. impl_to_bigint!(usize, FromPrimitive::from_usize);
  2039. impl_to_bigint!(u8, FromPrimitive::from_u8);
  2040. impl_to_bigint!(u16, FromPrimitive::from_u16);
  2041. impl_to_bigint!(u32, FromPrimitive::from_u32);
  2042. impl_to_bigint!(u64, FromPrimitive::from_u64);
  2043. impl_to_bigint!(f32, FromPrimitive::from_f32);
  2044. impl_to_bigint!(f64, FromPrimitive::from_f64);
  2045. pub trait RandBigInt {
  2046. /// Generate a random `BigUint` of the given bit size.
  2047. fn gen_biguint(&mut self, bit_size: usize) -> BigUint;
  2048. /// Generate a random BigInt of the given bit size.
  2049. fn gen_bigint(&mut self, bit_size: usize) -> BigInt;
  2050. /// Generate a random `BigUint` less than the given bound. Fails
  2051. /// when the bound is zero.
  2052. fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint;
  2053. /// Generate a random `BigUint` within the given range. The lower
  2054. /// bound is inclusive; the upper bound is exclusive. Fails when
  2055. /// the upper bound is not greater than the lower bound.
  2056. fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint;
  2057. /// Generate a random `BigInt` within the given range. The lower
  2058. /// bound is inclusive; the upper bound is exclusive. Fails when
  2059. /// the upper bound is not greater than the lower bound.
  2060. fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt;
  2061. }
  2062. impl<R: Rng> RandBigInt for R {
  2063. fn gen_biguint(&mut self, bit_size: usize) -> BigUint {
  2064. let (digits, rem) = bit_size.div_rem(&big_digit::BITS);
  2065. let mut data = Vec::with_capacity(digits+1);
  2066. for _ in 0 .. digits {
  2067. data.push(self.gen());
  2068. }
  2069. if rem > 0 {
  2070. let final_digit: BigDigit = self.gen();
  2071. data.push(final_digit >> (big_digit::BITS - rem));
  2072. }
  2073. BigUint::new(data)
  2074. }
  2075. fn gen_bigint(&mut self, bit_size: usize) -> BigInt {
  2076. // Generate a random BigUint...
  2077. let biguint = self.gen_biguint(bit_size);
  2078. // ...and then randomly assign it a Sign...
  2079. let sign = if biguint.is_zero() {
  2080. // ...except that if the BigUint is zero, we need to try
  2081. // again with probability 0.5. This is because otherwise,
  2082. // the probability of generating a zero BigInt would be
  2083. // double that of any other number.
  2084. if self.gen() {
  2085. return self.gen_bigint(bit_size);
  2086. } else {
  2087. NoSign
  2088. }
  2089. } else if self.gen() {
  2090. Plus
  2091. } else {
  2092. Minus
  2093. };
  2094. BigInt::from_biguint(sign, biguint)
  2095. }
  2096. fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint {
  2097. assert!(!bound.is_zero());
  2098. let bits = bound.bits();
  2099. loop {
  2100. let n = self.gen_biguint(bits);
  2101. if n < *bound { return n; }
  2102. }
  2103. }
  2104. fn gen_biguint_range(&mut self,
  2105. lbound: &BigUint,
  2106. ubound: &BigUint)
  2107. -> BigUint {
  2108. assert!(*lbound < *ubound);
  2109. return lbound + self.gen_biguint_below(&(ubound - lbound));
  2110. }
  2111. fn gen_bigint_range(&mut self,
  2112. lbound: &BigInt,
  2113. ubound: &BigInt)
  2114. -> BigInt {
  2115. assert!(*lbound < *ubound);
  2116. let delta = (ubound - lbound).to_biguint().unwrap();
  2117. return lbound + self.gen_biguint_below(&delta).to_bigint().unwrap();
  2118. }
  2119. }
  2120. impl BigInt {
  2121. /// Creates and initializes a BigInt.
  2122. ///
  2123. /// The digits are in little-endian base 2^32.
  2124. #[inline]
  2125. pub fn new(sign: Sign, digits: Vec<BigDigit>) -> BigInt {
  2126. BigInt::from_biguint(sign, BigUint::new(digits))
  2127. }
  2128. /// Creates and initializes a `BigInt`.
  2129. ///
  2130. /// The digits are in little-endian base 2^32.
  2131. #[inline]
  2132. pub fn from_biguint(sign: Sign, data: BigUint) -> BigInt {
  2133. if sign == NoSign || data.is_zero() {
  2134. return BigInt { sign: NoSign, data: Zero::zero() };
  2135. }
  2136. BigInt { sign: sign, data: data }
  2137. }
  2138. /// Creates and initializes a `BigInt`.
  2139. #[inline]
  2140. pub fn from_slice(sign: Sign, slice: &[BigDigit]) -> BigInt {
  2141. BigInt::from_biguint(sign, BigUint::from_slice(slice))
  2142. }
  2143. /// Creates and initializes a `BigInt`.
  2144. ///
  2145. /// The bytes are in big-endian byte order.
  2146. ///
  2147. /// # Examples
  2148. ///
  2149. /// ```
  2150. /// use num::bigint::{BigInt, Sign};
  2151. ///
  2152. /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"A"),
  2153. /// BigInt::parse_bytes(b"65", 10).unwrap());
  2154. /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AA"),
  2155. /// BigInt::parse_bytes(b"16705", 10).unwrap());
  2156. /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AB"),
  2157. /// BigInt::parse_bytes(b"16706", 10).unwrap());
  2158. /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"Hello world!"),
  2159. /// BigInt::parse_bytes(b"22405534230753963835153736737", 10).unwrap());
  2160. /// ```
  2161. #[inline]
  2162. pub fn from_bytes_be(sign: Sign, bytes: &[u8]) -> BigInt {
  2163. BigInt::from_biguint(sign, BigUint::from_bytes_be(bytes))
  2164. }
  2165. /// Creates and initializes a `BigInt`.
  2166. ///
  2167. /// The bytes are in little-endian byte order.
  2168. #[inline]
  2169. pub fn from_bytes_le(sign: Sign, bytes: &[u8]) -> BigInt {
  2170. BigInt::from_biguint(sign, BigUint::from_bytes_le(bytes))
  2171. }
  2172. /// Returns the sign and the byte representation of the `BigInt` in little-endian byte order.
  2173. ///
  2174. /// # Examples
  2175. ///
  2176. /// ```
  2177. /// use num::bigint::{ToBigInt, Sign};
  2178. ///
  2179. /// let i = -1125.to_bigint().unwrap();
  2180. /// assert_eq!(i.to_bytes_le(), (Sign::Minus, vec![101, 4]));
  2181. /// ```
  2182. #[inline]
  2183. pub fn to_bytes_le(&self) -> (Sign, Vec<u8>) {
  2184. (self.sign, self.data.to_bytes_le())
  2185. }
  2186. /// Returns the sign and the byte representation of the `BigInt` in big-endian byte order.
  2187. ///
  2188. /// # Examples
  2189. ///
  2190. /// ```
  2191. /// use num::bigint::{ToBigInt, Sign};
  2192. ///
  2193. /// let i = -1125.to_bigint().unwrap();
  2194. /// assert_eq!(i.to_bytes_be(), (Sign::Minus, vec![4, 101]));
  2195. /// ```
  2196. #[inline]
  2197. pub fn to_bytes_be(&self) -> (Sign, Vec<u8>) {
  2198. (self.sign, self.data.to_bytes_be())
  2199. }
  2200. /// Returns the integer formatted as a string in the given radix.
  2201. /// `radix` must be in the range `[2, 36]`.
  2202. ///
  2203. /// # Examples
  2204. ///
  2205. /// ```
  2206. /// use num::bigint::BigInt;
  2207. ///
  2208. /// let i = BigInt::parse_bytes(b"ff", 16).unwrap();
  2209. /// assert_eq!(i.to_str_radix(16), "ff");
  2210. /// ```
  2211. #[inline]
  2212. pub fn to_str_radix(&self, radix: u32) -> String {
  2213. let mut v = to_str_radix_reversed(&self.data, radix);
  2214. if self.is_negative() {
  2215. v.push(b'-');
  2216. }
  2217. v.reverse();
  2218. unsafe { String::from_utf8_unchecked(v) }
  2219. }
  2220. /// Returns the sign of the `BigInt` as a `Sign`.
  2221. ///
  2222. /// # Examples
  2223. ///
  2224. /// ```
  2225. /// use num::bigint::{ToBigInt, Sign};
  2226. ///
  2227. /// assert_eq!(ToBigInt::to_bigint(&1234).unwrap().sign(), Sign::Plus);
  2228. /// assert_eq!(ToBigInt::to_bigint(&-4321).unwrap().sign(), Sign::Minus);
  2229. /// assert_eq!(ToBigInt::to_bigint(&0).unwrap().sign(), Sign::NoSign);
  2230. /// ```
  2231. #[inline]
  2232. pub fn sign(&self) -> Sign {
  2233. self.sign
  2234. }
  2235. /// Creates and initializes a `BigInt`.
  2236. ///
  2237. /// # Examples
  2238. ///
  2239. /// ```
  2240. /// use num::bigint::{BigInt, ToBigInt};
  2241. ///
  2242. /// assert_eq!(BigInt::parse_bytes(b"1234", 10), ToBigInt::to_bigint(&1234));
  2243. /// assert_eq!(BigInt::parse_bytes(b"ABCD", 16), ToBigInt::to_bigint(&0xABCD));
  2244. /// assert_eq!(BigInt::parse_bytes(b"G", 16), None);
  2245. /// ```
  2246. #[inline]
  2247. pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigInt> {
  2248. str::from_utf8(buf).ok().and_then(|s| BigInt::from_str_radix(s, radix).ok())
  2249. }
  2250. /// Converts this `BigInt` into a `BigUint`, if it's not negative.
  2251. #[inline]
  2252. pub fn to_biguint(&self) -> Option<BigUint> {
  2253. match self.sign {
  2254. Plus => Some(self.data.clone()),
  2255. NoSign => Some(Zero::zero()),
  2256. Minus => None
  2257. }
  2258. }
  2259. #[inline]
  2260. pub fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
  2261. return Some(self.add(v));
  2262. }
  2263. #[inline]
  2264. pub fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
  2265. return Some(self.sub(v));
  2266. }
  2267. #[inline]
  2268. pub fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
  2269. return Some(self.mul(v));
  2270. }
  2271. #[inline]
  2272. pub fn checked_div(&self, v: &BigInt) -> Option<BigInt> {
  2273. if v.is_zero() {
  2274. return None;
  2275. }
  2276. return Some(self.div(v));
  2277. }
  2278. }
  2279. #[derive(Debug, PartialEq)]
  2280. pub enum ParseBigIntError {
  2281. ParseInt(ParseIntError),
  2282. Other,
  2283. }
  2284. impl fmt::Display for ParseBigIntError {
  2285. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  2286. match self {
  2287. &ParseBigIntError::ParseInt(ref e) => e.fmt(f),
  2288. &ParseBigIntError::Other => "failed to parse provided string".fmt(f)
  2289. }
  2290. }
  2291. }
  2292. impl Error for ParseBigIntError {
  2293. fn description(&self) -> &str { "failed to parse bigint/biguint" }
  2294. }
  2295. impl From<ParseIntError> for ParseBigIntError {
  2296. fn from(err: ParseIntError) -> ParseBigIntError {
  2297. ParseBigIntError::ParseInt(err)
  2298. }
  2299. }
  2300. #[cfg(test)]
  2301. mod biguint_tests {
  2302. use Integer;
  2303. use super::{BigDigit, BigUint, ToBigUint, big_digit};
  2304. use super::{BigInt, RandBigInt, ToBigInt};
  2305. use super::Sign::Plus;
  2306. use std::cmp::Ordering::{Less, Equal, Greater};
  2307. use std::{f32, f64};
  2308. use std::i64;
  2309. use std::iter::repeat;
  2310. use std::str::FromStr;
  2311. use std::{u8, u16, u32, u64, usize};
  2312. use rand::thread_rng;
  2313. use {Num, Zero, One, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv};
  2314. use {ToPrimitive, FromPrimitive};
  2315. use Float;
  2316. /// Assert that an op works for all val/ref combinations
  2317. macro_rules! assert_op {
  2318. ($left:ident $op:tt $right:ident == $expected:expr) => {
  2319. assert_eq!((&$left) $op (&$right), $expected);
  2320. assert_eq!((&$left) $op $right.clone(), $expected);
  2321. assert_eq!($left.clone() $op (&$right), $expected);
  2322. assert_eq!($left.clone() $op $right.clone(), $expected);
  2323. };
  2324. }
  2325. #[test]
  2326. fn test_from_slice() {
  2327. fn check(slice: &[BigDigit], data: &[BigDigit]) {
  2328. assert!(BigUint::from_slice(slice).data == data);
  2329. }
  2330. check(&[1], &[1]);
  2331. check(&[0, 0, 0], &[]);
  2332. check(&[1, 2, 0, 0], &[1, 2]);
  2333. check(&[0, 0, 1, 2], &[0, 0, 1, 2]);
  2334. check(&[0, 0, 1, 2, 0, 0], &[0, 0, 1, 2]);
  2335. check(&[-1i32 as BigDigit], &[-1i32 as BigDigit]);
  2336. }
  2337. #[test]
  2338. fn test_from_bytes_be() {
  2339. fn check(s: &str, result: &str) {
  2340. assert_eq!(BigUint::from_bytes_be(s.as_bytes()),
  2341. BigUint::parse_bytes(result.as_bytes(), 10).unwrap());
  2342. }
  2343. check("A", "65");
  2344. check("AA", "16705");
  2345. check("AB", "16706");
  2346. check("Hello world!", "22405534230753963835153736737");
  2347. assert_eq!(BigUint::from_bytes_be(&[]), Zero::zero());
  2348. }
  2349. #[test]
  2350. fn test_to_bytes_be() {
  2351. fn check(s: &str, result: &str) {
  2352. let b = BigUint::parse_bytes(result.as_bytes(), 10).unwrap();
  2353. assert_eq!(b.to_bytes_be(), s.as_bytes());
  2354. }
  2355. check("A", "65");
  2356. check("AA", "16705");
  2357. check("AB", "16706");
  2358. check("Hello world!", "22405534230753963835153736737");
  2359. let b: BigUint = Zero::zero();
  2360. assert_eq!(b.to_bytes_be(), [0]);
  2361. // Test with leading/trailing zero bytes and a full BigDigit of value 0
  2362. let b = BigUint::from_str_radix("00010000000000000200", 16).unwrap();
  2363. assert_eq!(b.to_bytes_be(), [1, 0, 0, 0, 0, 0, 0, 2, 0]);
  2364. }
  2365. #[test]
  2366. fn test_from_bytes_le() {
  2367. fn check(s: &str, result: &str) {
  2368. assert_eq!(BigUint::from_bytes_le(s.as_bytes()),
  2369. BigUint::parse_bytes(result.as_bytes(), 10).unwrap());
  2370. }
  2371. check("A", "65");
  2372. check("AA", "16705");
  2373. check("BA", "16706");
  2374. check("!dlrow olleH", "22405534230753963835153736737");
  2375. assert_eq!(BigUint::from_bytes_le(&[]), Zero::zero());
  2376. }
  2377. #[test]
  2378. fn test_to_bytes_le() {
  2379. fn check(s: &str, result: &str) {
  2380. let b = BigUint::parse_bytes(result.as_bytes(), 10).unwrap();
  2381. assert_eq!(b.to_bytes_le(), s.as_bytes());
  2382. }
  2383. check("A", "65");
  2384. check("AA", "16705");
  2385. check("BA", "16706");
  2386. check("!dlrow olleH", "22405534230753963835153736737");
  2387. let b: BigUint = Zero::zero();
  2388. assert_eq!(b.to_bytes_le(), [0]);
  2389. // Test with leading/trailing zero bytes and a full BigDigit of value 0
  2390. let b = BigUint::from_str_radix("00010000000000000200", 16).unwrap();
  2391. assert_eq!(b.to_bytes_le(), [0, 2, 0, 0, 0, 0, 0, 0, 1]);
  2392. }
  2393. #[test]
  2394. fn test_cmp() {
  2395. let data: [&[_]; 7] = [ &[], &[1], &[2], &[!0], &[0, 1], &[2, 1], &[1, 1, 1] ];
  2396. let data: Vec<BigUint> = data.iter().map(|v| BigUint::from_slice(*v)).collect();
  2397. for (i, ni) in data.iter().enumerate() {
  2398. for (j0, nj) in data[i..].iter().enumerate() {
  2399. let j = j0 + i;
  2400. if i == j {
  2401. assert_eq!(ni.cmp(nj), Equal);
  2402. assert_eq!(nj.cmp(ni), Equal);
  2403. assert_eq!(ni, nj);
  2404. assert!(!(ni != nj));
  2405. assert!(ni <= nj);
  2406. assert!(ni >= nj);
  2407. assert!(!(ni < nj));
  2408. assert!(!(ni > nj));
  2409. } else {
  2410. assert_eq!(ni.cmp(nj), Less);
  2411. assert_eq!(nj.cmp(ni), Greater);
  2412. assert!(!(ni == nj));
  2413. assert!(ni != nj);
  2414. assert!(ni <= nj);
  2415. assert!(!(ni >= nj));
  2416. assert!(ni < nj);
  2417. assert!(!(ni > nj));
  2418. assert!(!(nj <= ni));
  2419. assert!(nj >= ni);
  2420. assert!(!(nj < ni));
  2421. assert!(nj > ni);
  2422. }
  2423. }
  2424. }
  2425. }
  2426. #[test]
  2427. fn test_hash() {
  2428. let a = BigUint::new(vec!());
  2429. let b = BigUint::new(vec!(0));
  2430. let c = BigUint::new(vec!(1));
  2431. let d = BigUint::new(vec!(1,0,0,0,0,0));
  2432. let e = BigUint::new(vec!(0,0,0,0,0,1));
  2433. assert!(::hash(&a) == ::hash(&b));
  2434. assert!(::hash(&b) != ::hash(&c));
  2435. assert!(::hash(&c) == ::hash(&d));
  2436. assert!(::hash(&d) != ::hash(&e));
  2437. }
  2438. const BIT_TESTS: &'static [(&'static [BigDigit],
  2439. &'static [BigDigit],
  2440. &'static [BigDigit],
  2441. &'static [BigDigit],
  2442. &'static [BigDigit])] = &[
  2443. // LEFT RIGHT AND OR XOR
  2444. ( &[], &[], &[], &[], &[] ),
  2445. ( &[268, 482, 17], &[964, 54], &[260, 34], &[972, 502, 17], &[712, 468, 17] ),
  2446. ];
  2447. #[test]
  2448. fn test_bitand() {
  2449. for elm in BIT_TESTS {
  2450. let (a_vec, b_vec, c_vec, _, _) = *elm;
  2451. let a = BigUint::from_slice(a_vec);
  2452. let b = BigUint::from_slice(b_vec);
  2453. let c = BigUint::from_slice(c_vec);
  2454. assert_op!(a & b == c);
  2455. assert_op!(b & a == c);
  2456. }
  2457. }
  2458. #[test]
  2459. fn test_bitor() {
  2460. for elm in BIT_TESTS {
  2461. let (a_vec, b_vec, _, c_vec, _) = *elm;
  2462. let a = BigUint::from_slice(a_vec);
  2463. let b = BigUint::from_slice(b_vec);
  2464. let c = BigUint::from_slice(c_vec);
  2465. assert_op!(a | b == c);
  2466. assert_op!(b | a == c);
  2467. }
  2468. }
  2469. #[test]
  2470. fn test_bitxor() {
  2471. for elm in BIT_TESTS {
  2472. let (a_vec, b_vec, _, _, c_vec) = *elm;
  2473. let a = BigUint::from_slice(a_vec);
  2474. let b = BigUint::from_slice(b_vec);
  2475. let c = BigUint::from_slice(c_vec);
  2476. assert_op!(a ^ b == c);
  2477. assert_op!(b ^ a == c);
  2478. assert_op!(a ^ c == b);
  2479. assert_op!(c ^ a == b);
  2480. assert_op!(b ^ c == a);
  2481. assert_op!(c ^ b == a);
  2482. }
  2483. }
  2484. #[test]
  2485. fn test_shl() {
  2486. fn check(s: &str, shift: usize, ans: &str) {
  2487. let opt_biguint = BigUint::from_str_radix(s, 16).ok();
  2488. let bu = (opt_biguint.unwrap() << shift).to_str_radix(16);
  2489. assert_eq!(bu, ans);
  2490. }
  2491. check("0", 3, "0");
  2492. check("1", 3, "8");
  2493. check("1\
  2494. 0000\
  2495. 0000\
  2496. 0000\
  2497. 0001\
  2498. 0000\
  2499. 0000\
  2500. 0000\
  2501. 0001",
  2502. 3,
  2503. "8\
  2504. 0000\
  2505. 0000\
  2506. 0000\
  2507. 0008\
  2508. 0000\
  2509. 0000\
  2510. 0000\
  2511. 0008");
  2512. check("1\
  2513. 0000\
  2514. 0001\
  2515. 0000\
  2516. 0001",
  2517. 2,
  2518. "4\
  2519. 0000\
  2520. 0004\
  2521. 0000\
  2522. 0004");
  2523. check("1\
  2524. 0001\
  2525. 0001",
  2526. 1,
  2527. "2\
  2528. 0002\
  2529. 0002");
  2530. check("\
  2531. 4000\
  2532. 0000\
  2533. 0000\
  2534. 0000",
  2535. 3,
  2536. "2\
  2537. 0000\
  2538. 0000\
  2539. 0000\
  2540. 0000");
  2541. check("4000\
  2542. 0000",
  2543. 2,
  2544. "1\
  2545. 0000\
  2546. 0000");
  2547. check("4000",
  2548. 2,
  2549. "1\
  2550. 0000");
  2551. check("4000\
  2552. 0000\
  2553. 0000\
  2554. 0000",
  2555. 67,
  2556. "2\
  2557. 0000\
  2558. 0000\
  2559. 0000\
  2560. 0000\
  2561. 0000\
  2562. 0000\
  2563. 0000\
  2564. 0000");
  2565. check("4000\
  2566. 0000",
  2567. 35,
  2568. "2\
  2569. 0000\
  2570. 0000\
  2571. 0000\
  2572. 0000");
  2573. check("4000",
  2574. 19,
  2575. "2\
  2576. 0000\
  2577. 0000");
  2578. check("fedc\
  2579. ba98\
  2580. 7654\
  2581. 3210\
  2582. fedc\
  2583. ba98\
  2584. 7654\
  2585. 3210",
  2586. 4,
  2587. "f\
  2588. edcb\
  2589. a987\
  2590. 6543\
  2591. 210f\
  2592. edcb\
  2593. a987\
  2594. 6543\
  2595. 2100");
  2596. check("88887777666655554444333322221111", 16,
  2597. "888877776666555544443333222211110000");
  2598. }
  2599. #[test]
  2600. fn test_shr() {
  2601. fn check(s: &str, shift: usize, ans: &str) {
  2602. let opt_biguint = BigUint::from_str_radix(s, 16).ok();
  2603. let bu = (opt_biguint.unwrap() >> shift).to_str_radix(16);
  2604. assert_eq!(bu, ans);
  2605. }
  2606. check("0", 3, "0");
  2607. check("f", 3, "1");
  2608. check("1\
  2609. 0000\
  2610. 0000\
  2611. 0000\
  2612. 0001\
  2613. 0000\
  2614. 0000\
  2615. 0000\
  2616. 0001",
  2617. 3,
  2618. "2000\
  2619. 0000\
  2620. 0000\
  2621. 0000\
  2622. 2000\
  2623. 0000\
  2624. 0000\
  2625. 0000");
  2626. check("1\
  2627. 0000\
  2628. 0001\
  2629. 0000\
  2630. 0001",
  2631. 2,
  2632. "4000\
  2633. 0000\
  2634. 4000\
  2635. 0000");
  2636. check("1\
  2637. 0001\
  2638. 0001",
  2639. 1,
  2640. "8000\
  2641. 8000");
  2642. check("2\
  2643. 0000\
  2644. 0000\
  2645. 0000\
  2646. 0001\
  2647. 0000\
  2648. 0000\
  2649. 0000\
  2650. 0001",
  2651. 67,
  2652. "4000\
  2653. 0000\
  2654. 0000\
  2655. 0000");
  2656. check("2\
  2657. 0000\
  2658. 0001\
  2659. 0000\
  2660. 0001",
  2661. 35,
  2662. "4000\
  2663. 0000");
  2664. check("2\
  2665. 0001\
  2666. 0001",
  2667. 19,
  2668. "4000");
  2669. check("1\
  2670. 0000\
  2671. 0000\
  2672. 0000\
  2673. 0000",
  2674. 1,
  2675. "8000\
  2676. 0000\
  2677. 0000\
  2678. 0000");
  2679. check("1\
  2680. 0000\
  2681. 0000",
  2682. 1,
  2683. "8000\
  2684. 0000");
  2685. check("1\
  2686. 0000",
  2687. 1,
  2688. "8000");
  2689. check("f\
  2690. edcb\
  2691. a987\
  2692. 6543\
  2693. 210f\
  2694. edcb\
  2695. a987\
  2696. 6543\
  2697. 2100",
  2698. 4,
  2699. "fedc\
  2700. ba98\
  2701. 7654\
  2702. 3210\
  2703. fedc\
  2704. ba98\
  2705. 7654\
  2706. 3210");
  2707. check("888877776666555544443333222211110000", 16,
  2708. "88887777666655554444333322221111");
  2709. }
  2710. const N1: BigDigit = -1i32 as BigDigit;
  2711. const N2: BigDigit = -2i32 as BigDigit;
  2712. // `DoubleBigDigit` size dependent
  2713. #[test]
  2714. fn test_convert_i64() {
  2715. fn check(b1: BigUint, i: i64) {
  2716. let b2: BigUint = FromPrimitive::from_i64(i).unwrap();
  2717. assert!(b1 == b2);
  2718. assert!(b1.to_i64().unwrap() == i);
  2719. }
  2720. check(Zero::zero(), 0);
  2721. check(One::one(), 1);
  2722. check(i64::MAX.to_biguint().unwrap(), i64::MAX);
  2723. check(BigUint::new(vec!( )), 0);
  2724. check(BigUint::new(vec!( 1 )), (1 << (0*big_digit::BITS)));
  2725. check(BigUint::new(vec!(N1 )), (1 << (1*big_digit::BITS)) - 1);
  2726. check(BigUint::new(vec!( 0, 1 )), (1 << (1*big_digit::BITS)));
  2727. check(BigUint::new(vec!(N1, N1 >> 1)), i64::MAX);
  2728. assert_eq!(i64::MIN.to_biguint(), None);
  2729. assert_eq!(BigUint::new(vec!(N1, N1 )).to_i64(), None);
  2730. assert_eq!(BigUint::new(vec!( 0, 0, 1)).to_i64(), None);
  2731. assert_eq!(BigUint::new(vec!(N1, N1, N1)).to_i64(), None);
  2732. }
  2733. // `DoubleBigDigit` size dependent
  2734. #[test]
  2735. fn test_convert_u64() {
  2736. fn check(b1: BigUint, u: u64) {
  2737. let b2: BigUint = FromPrimitive::from_u64(u).unwrap();
  2738. assert!(b1 == b2);
  2739. assert!(b1.to_u64().unwrap() == u);
  2740. }
  2741. check(Zero::zero(), 0);
  2742. check(One::one(), 1);
  2743. check(u64::MIN.to_biguint().unwrap(), u64::MIN);
  2744. check(u64::MAX.to_biguint().unwrap(), u64::MAX);
  2745. check(BigUint::new(vec!( )), 0);
  2746. check(BigUint::new(vec!( 1 )), (1 << (0*big_digit::BITS)));
  2747. check(BigUint::new(vec!(N1 )), (1 << (1*big_digit::BITS)) - 1);
  2748. check(BigUint::new(vec!( 0, 1)), (1 << (1*big_digit::BITS)));
  2749. check(BigUint::new(vec!(N1, N1)), u64::MAX);
  2750. assert_eq!(BigUint::new(vec!( 0, 0, 1)).to_u64(), None);
  2751. assert_eq!(BigUint::new(vec!(N1, N1, N1)).to_u64(), None);
  2752. }
  2753. #[test]
  2754. fn test_convert_f32() {
  2755. fn check(b1: &BigUint, f: f32) {
  2756. let b2 = BigUint::from_f32(f).unwrap();
  2757. assert_eq!(b1, &b2);
  2758. assert_eq!(b1.to_f32().unwrap(), f);
  2759. }
  2760. check(&BigUint::zero(), 0.0);
  2761. check(&BigUint::one(), 1.0);
  2762. check(&BigUint::from(u16::MAX), 2.0.powi(16) - 1.0);
  2763. check(&BigUint::from(1u64 << 32), 2.0.powi(32));
  2764. check(&BigUint::from_slice(&[0, 0, 1]), 2.0.powi(64));
  2765. check(&((BigUint::one() << 100) + (BigUint::one() << 123)), 2.0.powi(100) + 2.0.powi(123));
  2766. check(&(BigUint::one() << 127), 2.0.powi(127));
  2767. check(&(BigUint::from((1u64 << 24) - 1) << (128 - 24)), f32::MAX);
  2768. // keeping all 24 digits with the bits at different offsets to the BigDigits
  2769. let x: u32 = 0b00000000101111011111011011011101;
  2770. let mut f = x as f32;
  2771. let mut b = BigUint::from(x);
  2772. for _ in 0..64 {
  2773. check(&b, f);
  2774. f *= 2.0;
  2775. b = b << 1;
  2776. }
  2777. // this number when rounded to f64 then f32 isn't the same as when rounded straight to f32
  2778. let n: u64 = 0b0000000000111111111111111111111111011111111111111111111111111111;
  2779. assert!((n as f64) as f32 != n as f32);
  2780. assert_eq!(BigUint::from(n).to_f32(), Some(n as f32));
  2781. // test rounding up with the bits at different offsets to the BigDigits
  2782. let mut f = ((1u64 << 25) - 1) as f32;
  2783. let mut b = BigUint::from(1u64 << 25);
  2784. for _ in 0..64 {
  2785. assert_eq!(b.to_f32(), Some(f));
  2786. f *= 2.0;
  2787. b = b << 1;
  2788. }
  2789. // rounding
  2790. assert_eq!(BigUint::from_f32(-1.0), None);
  2791. assert_eq!(BigUint::from_f32(-0.99999), Some(BigUint::zero()));
  2792. assert_eq!(BigUint::from_f32(-0.5), Some(BigUint::zero()));
  2793. assert_eq!(BigUint::from_f32(-0.0), Some(BigUint::zero()));
  2794. assert_eq!(BigUint::from_f32(f32::MIN_POSITIVE / 2.0), Some(BigUint::zero()));
  2795. assert_eq!(BigUint::from_f32(f32::MIN_POSITIVE), Some(BigUint::zero()));
  2796. assert_eq!(BigUint::from_f32(0.5), Some(BigUint::zero()));
  2797. assert_eq!(BigUint::from_f32(0.99999), Some(BigUint::zero()));
  2798. assert_eq!(BigUint::from_f32(f32::consts::E), Some(BigUint::from(2u32)));
  2799. assert_eq!(BigUint::from_f32(f32::consts::PI), Some(BigUint::from(3u32)));
  2800. // special float values
  2801. assert_eq!(BigUint::from_f32(f32::NAN), None);
  2802. assert_eq!(BigUint::from_f32(f32::INFINITY), None);
  2803. assert_eq!(BigUint::from_f32(f32::NEG_INFINITY), None);
  2804. assert_eq!(BigUint::from_f32(f32::MIN), None);
  2805. // largest BigUint that will round to a finite f32 value
  2806. let big_num = (BigUint::one() << 128) - BigUint::one() - (BigUint::one() << (128 - 25));
  2807. assert_eq!(big_num.to_f32(), Some(f32::MAX));
  2808. assert_eq!((big_num + BigUint::one()).to_f32(), None);
  2809. assert_eq!(((BigUint::one() << 128) - BigUint::one()).to_f32(), None);
  2810. assert_eq!((BigUint::one() << 128).to_f32(), None);
  2811. }
  2812. #[test]
  2813. fn test_convert_f64() {
  2814. fn check(b1: &BigUint, f: f64) {
  2815. let b2 = BigUint::from_f64(f).unwrap();
  2816. assert_eq!(b1, &b2);
  2817. assert_eq!(b1.to_f64().unwrap(), f);
  2818. }
  2819. check(&BigUint::zero(), 0.0);
  2820. check(&BigUint::one(), 1.0);
  2821. check(&BigUint::from(u32::MAX), 2.0.powi(32) - 1.0);
  2822. check(&BigUint::from(1u64 << 32), 2.0.powi(32));
  2823. check(&BigUint::from_slice(&[0, 0, 1]), 2.0.powi(64));
  2824. check(&((BigUint::one() << 100) + (BigUint::one() << 152)), 2.0.powi(100) + 2.0.powi(152));
  2825. check(&(BigUint::one() << 1023), 2.0.powi(1023));
  2826. check(&(BigUint::from((1u64 << 53) - 1) << (1024 - 53)), f64::MAX);
  2827. // keeping all 53 digits with the bits at different offsets to the BigDigits
  2828. let x: u64 = 0b0000000000011110111110110111111101110111101111011111011011011101;
  2829. let mut f = x as f64;
  2830. let mut b = BigUint::from(x);
  2831. for _ in 0..128 {
  2832. check(&b, f);
  2833. f *= 2.0;
  2834. b = b << 1;
  2835. }
  2836. // test rounding up with the bits at different offsets to the BigDigits
  2837. let mut f = ((1u64 << 54) - 1) as f64;
  2838. let mut b = BigUint::from(1u64 << 54);
  2839. for _ in 0..128 {
  2840. assert_eq!(b.to_f64(), Some(f));
  2841. f *= 2.0;
  2842. b = b << 1;
  2843. }
  2844. // rounding
  2845. assert_eq!(BigUint::from_f64(-1.0), None);
  2846. assert_eq!(BigUint::from_f64(-0.99999), Some(BigUint::zero()));
  2847. assert_eq!(BigUint::from_f64(-0.5), Some(BigUint::zero()));
  2848. assert_eq!(BigUint::from_f64(-0.0), Some(BigUint::zero()));
  2849. assert_eq!(BigUint::from_f64(f64::MIN_POSITIVE / 2.0), Some(BigUint::zero()));
  2850. assert_eq!(BigUint::from_f64(f64::MIN_POSITIVE), Some(BigUint::zero()));
  2851. assert_eq!(BigUint::from_f64(0.5), Some(BigUint::zero()));
  2852. assert_eq!(BigUint::from_f64(0.99999), Some(BigUint::zero()));
  2853. assert_eq!(BigUint::from_f64(f64::consts::E), Some(BigUint::from(2u32)));
  2854. assert_eq!(BigUint::from_f64(f64::consts::PI), Some(BigUint::from(3u32)));
  2855. // special float values
  2856. assert_eq!(BigUint::from_f64(f64::NAN), None);
  2857. assert_eq!(BigUint::from_f64(f64::INFINITY), None);
  2858. assert_eq!(BigUint::from_f64(f64::NEG_INFINITY), None);
  2859. assert_eq!(BigUint::from_f64(f64::MIN), None);
  2860. // largest BigUint that will round to a finite f64 value
  2861. let big_num = (BigUint::one() << 1024) - BigUint::one() - (BigUint::one() << (1024 - 54));
  2862. assert_eq!(big_num.to_f64(), Some(f64::MAX));
  2863. assert_eq!((big_num + BigUint::one()).to_f64(), None);
  2864. assert_eq!(((BigInt::one() << 1024) - BigInt::one()).to_f64(), None);
  2865. assert_eq!((BigUint::one() << 1024).to_f64(), None);
  2866. }
  2867. #[test]
  2868. fn test_convert_to_bigint() {
  2869. fn check(n: BigUint, ans: BigInt) {
  2870. assert_eq!(n.to_bigint().unwrap(), ans);
  2871. assert_eq!(n.to_bigint().unwrap().to_biguint().unwrap(), n);
  2872. }
  2873. check(Zero::zero(), Zero::zero());
  2874. check(BigUint::new(vec!(1,2,3)),
  2875. BigInt::from_biguint(Plus, BigUint::new(vec!(1,2,3))));
  2876. }
  2877. #[test]
  2878. fn test_convert_from_uint() {
  2879. macro_rules! check {
  2880. ($ty:ident, $max:expr) => {
  2881. assert_eq!(BigUint::from($ty::zero()), BigUint::zero());
  2882. assert_eq!(BigUint::from($ty::one()), BigUint::one());
  2883. assert_eq!(BigUint::from($ty::MAX - $ty::one()), $max - BigUint::one());
  2884. assert_eq!(BigUint::from($ty::MAX), $max);
  2885. }
  2886. }
  2887. check!(u8, BigUint::from_slice(&[u8::MAX as BigDigit]));
  2888. check!(u16, BigUint::from_slice(&[u16::MAX as BigDigit]));
  2889. check!(u32, BigUint::from_slice(&[u32::MAX]));
  2890. check!(u64, BigUint::from_slice(&[u32::MAX, u32::MAX]));
  2891. check!(usize, BigUint::from(usize::MAX as u64));
  2892. }
  2893. const SUM_TRIPLES: &'static [(&'static [BigDigit],
  2894. &'static [BigDigit],
  2895. &'static [BigDigit])] = &[
  2896. (&[], &[], &[]),
  2897. (&[], &[ 1], &[ 1]),
  2898. (&[ 1], &[ 1], &[ 2]),
  2899. (&[ 1], &[ 1, 1], &[ 2, 1]),
  2900. (&[ 1], &[N1], &[ 0, 1]),
  2901. (&[ 1], &[N1, N1], &[ 0, 0, 1]),
  2902. (&[N1, N1], &[N1, N1], &[N2, N1, 1]),
  2903. (&[ 1, 1, 1], &[N1, N1], &[ 0, 1, 2]),
  2904. (&[ 2, 2, 1], &[N1, N2], &[ 1, 1, 2])
  2905. ];
  2906. #[test]
  2907. fn test_add() {
  2908. for elm in SUM_TRIPLES.iter() {
  2909. let (a_vec, b_vec, c_vec) = *elm;
  2910. let a = BigUint::from_slice(a_vec);
  2911. let b = BigUint::from_slice(b_vec);
  2912. let c = BigUint::from_slice(c_vec);
  2913. assert_op!(a + b == c);
  2914. assert_op!(b + a == c);
  2915. }
  2916. }
  2917. #[test]
  2918. fn test_sub() {
  2919. for elm in SUM_TRIPLES.iter() {
  2920. let (a_vec, b_vec, c_vec) = *elm;
  2921. let a = BigUint::from_slice(a_vec);
  2922. let b = BigUint::from_slice(b_vec);
  2923. let c = BigUint::from_slice(c_vec);
  2924. assert_op!(c - a == b);
  2925. assert_op!(c - b == a);
  2926. }
  2927. }
  2928. #[test]
  2929. #[should_panic]
  2930. fn test_sub_fail_on_underflow() {
  2931. let (a, b) : (BigUint, BigUint) = (Zero::zero(), One::one());
  2932. a - b;
  2933. }
  2934. const M: u32 = ::std::u32::MAX;
  2935. const MUL_TRIPLES: &'static [(&'static [BigDigit],
  2936. &'static [BigDigit],
  2937. &'static [BigDigit])] = &[
  2938. (&[], &[], &[]),
  2939. (&[], &[ 1], &[]),
  2940. (&[ 2], &[], &[]),
  2941. (&[ 1], &[ 1], &[1]),
  2942. (&[ 2], &[ 3], &[ 6]),
  2943. (&[ 1], &[ 1, 1, 1], &[1, 1, 1]),
  2944. (&[ 1, 2, 3], &[ 3], &[ 3, 6, 9]),
  2945. (&[ 1, 1, 1], &[N1], &[N1, N1, N1]),
  2946. (&[ 1, 2, 3], &[N1], &[N1, N2, N2, 2]),
  2947. (&[ 1, 2, 3, 4], &[N1], &[N1, N2, N2, N2, 3]),
  2948. (&[N1], &[N1], &[ 1, N2]),
  2949. (&[N1, N1], &[N1], &[ 1, N1, N2]),
  2950. (&[N1, N1, N1], &[N1], &[ 1, N1, N1, N2]),
  2951. (&[N1, N1, N1, N1], &[N1], &[ 1, N1, N1, N1, N2]),
  2952. (&[ M/2 + 1], &[ 2], &[ 0, 1]),
  2953. (&[0, M/2 + 1], &[ 2], &[ 0, 0, 1]),
  2954. (&[ 1, 2], &[ 1, 2, 3], &[1, 4, 7, 6]),
  2955. (&[N1, N1], &[N1, N1, N1], &[1, 0, N1, N2, N1]),
  2956. (&[N1, N1, N1], &[N1, N1, N1, N1], &[1, 0, 0, N1, N2, N1, N1]),
  2957. (&[ 0, 0, 1], &[ 1, 2, 3], &[0, 0, 1, 2, 3]),
  2958. (&[ 0, 0, 1], &[ 0, 0, 0, 1], &[0, 0, 0, 0, 0, 1])
  2959. ];
  2960. const DIV_REM_QUADRUPLES: &'static [(&'static [BigDigit],
  2961. &'static [BigDigit],
  2962. &'static [BigDigit],
  2963. &'static [BigDigit])]
  2964. = &[
  2965. (&[ 1], &[ 2], &[], &[1]),
  2966. (&[ 1, 1], &[ 2], &[ M/2+1], &[1]),
  2967. (&[ 1, 1, 1], &[ 2], &[ M/2+1, M/2+1], &[1]),
  2968. (&[ 0, 1], &[N1], &[1], &[1]),
  2969. (&[N1, N1], &[N2], &[2, 1], &[3])
  2970. ];
  2971. #[test]
  2972. fn test_mul() {
  2973. for elm in MUL_TRIPLES.iter() {
  2974. let (a_vec, b_vec, c_vec) = *elm;
  2975. let a = BigUint::from_slice(a_vec);
  2976. let b = BigUint::from_slice(b_vec);
  2977. let c = BigUint::from_slice(c_vec);
  2978. assert_op!(a * b == c);
  2979. assert_op!(b * a == c);
  2980. }
  2981. for elm in DIV_REM_QUADRUPLES.iter() {
  2982. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  2983. let a = BigUint::from_slice(a_vec);
  2984. let b = BigUint::from_slice(b_vec);
  2985. let c = BigUint::from_slice(c_vec);
  2986. let d = BigUint::from_slice(d_vec);
  2987. assert!(a == &b * &c + &d);
  2988. assert!(a == &c * &b + &d);
  2989. }
  2990. }
  2991. #[test]
  2992. fn test_div_rem() {
  2993. for elm in MUL_TRIPLES.iter() {
  2994. let (a_vec, b_vec, c_vec) = *elm;
  2995. let a = BigUint::from_slice(a_vec);
  2996. let b = BigUint::from_slice(b_vec);
  2997. let c = BigUint::from_slice(c_vec);
  2998. if !a.is_zero() {
  2999. assert_op!(c / a == b);
  3000. assert_op!(c % a == Zero::zero());
  3001. assert_eq!(c.div_rem(&a), (b.clone(), Zero::zero()));
  3002. }
  3003. if !b.is_zero() {
  3004. assert_op!(c / b == a);
  3005. assert_op!(c % b == Zero::zero());
  3006. assert_eq!(c.div_rem(&b), (a.clone(), Zero::zero()));
  3007. }
  3008. }
  3009. for elm in DIV_REM_QUADRUPLES.iter() {
  3010. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  3011. let a = BigUint::from_slice(a_vec);
  3012. let b = BigUint::from_slice(b_vec);
  3013. let c = BigUint::from_slice(c_vec);
  3014. let d = BigUint::from_slice(d_vec);
  3015. if !b.is_zero() {
  3016. assert_op!(a / b == c);
  3017. assert_op!(a % b == d);
  3018. assert!(a.div_rem(&b) == (c, d));
  3019. }
  3020. }
  3021. }
  3022. #[test]
  3023. fn test_checked_add() {
  3024. for elm in SUM_TRIPLES.iter() {
  3025. let (a_vec, b_vec, c_vec) = *elm;
  3026. let a = BigUint::from_slice(a_vec);
  3027. let b = BigUint::from_slice(b_vec);
  3028. let c = BigUint::from_slice(c_vec);
  3029. assert!(a.checked_add(&b).unwrap() == c);
  3030. assert!(b.checked_add(&a).unwrap() == c);
  3031. }
  3032. }
  3033. #[test]
  3034. fn test_checked_sub() {
  3035. for elm in SUM_TRIPLES.iter() {
  3036. let (a_vec, b_vec, c_vec) = *elm;
  3037. let a = BigUint::from_slice(a_vec);
  3038. let b = BigUint::from_slice(b_vec);
  3039. let c = BigUint::from_slice(c_vec);
  3040. assert!(c.checked_sub(&a).unwrap() == b);
  3041. assert!(c.checked_sub(&b).unwrap() == a);
  3042. if a > c {
  3043. assert!(a.checked_sub(&c).is_none());
  3044. }
  3045. if b > c {
  3046. assert!(b.checked_sub(&c).is_none());
  3047. }
  3048. }
  3049. }
  3050. #[test]
  3051. fn test_checked_mul() {
  3052. for elm in MUL_TRIPLES.iter() {
  3053. let (a_vec, b_vec, c_vec) = *elm;
  3054. let a = BigUint::from_slice(a_vec);
  3055. let b = BigUint::from_slice(b_vec);
  3056. let c = BigUint::from_slice(c_vec);
  3057. assert!(a.checked_mul(&b).unwrap() == c);
  3058. assert!(b.checked_mul(&a).unwrap() == c);
  3059. }
  3060. for elm in DIV_REM_QUADRUPLES.iter() {
  3061. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  3062. let a = BigUint::from_slice(a_vec);
  3063. let b = BigUint::from_slice(b_vec);
  3064. let c = BigUint::from_slice(c_vec);
  3065. let d = BigUint::from_slice(d_vec);
  3066. assert!(a == b.checked_mul(&c).unwrap() + &d);
  3067. assert!(a == c.checked_mul(&b).unwrap() + &d);
  3068. }
  3069. }
  3070. #[test]
  3071. fn test_checked_div() {
  3072. for elm in MUL_TRIPLES.iter() {
  3073. let (a_vec, b_vec, c_vec) = *elm;
  3074. let a = BigUint::from_slice(a_vec);
  3075. let b = BigUint::from_slice(b_vec);
  3076. let c = BigUint::from_slice(c_vec);
  3077. if !a.is_zero() {
  3078. assert!(c.checked_div(&a).unwrap() == b);
  3079. }
  3080. if !b.is_zero() {
  3081. assert!(c.checked_div(&b).unwrap() == a);
  3082. }
  3083. assert!(c.checked_div(&Zero::zero()).is_none());
  3084. }
  3085. }
  3086. #[test]
  3087. fn test_gcd() {
  3088. fn check(a: usize, b: usize, c: usize) {
  3089. let big_a: BigUint = FromPrimitive::from_usize(a).unwrap();
  3090. let big_b: BigUint = FromPrimitive::from_usize(b).unwrap();
  3091. let big_c: BigUint = FromPrimitive::from_usize(c).unwrap();
  3092. assert_eq!(big_a.gcd(&big_b), big_c);
  3093. }
  3094. check(10, 2, 2);
  3095. check(10, 3, 1);
  3096. check(0, 3, 3);
  3097. check(3, 3, 3);
  3098. check(56, 42, 14);
  3099. }
  3100. #[test]
  3101. fn test_lcm() {
  3102. fn check(a: usize, b: usize, c: usize) {
  3103. let big_a: BigUint = FromPrimitive::from_usize(a).unwrap();
  3104. let big_b: BigUint = FromPrimitive::from_usize(b).unwrap();
  3105. let big_c: BigUint = FromPrimitive::from_usize(c).unwrap();
  3106. assert_eq!(big_a.lcm(&big_b), big_c);
  3107. }
  3108. check(1, 0, 0);
  3109. check(0, 1, 0);
  3110. check(1, 1, 1);
  3111. check(8, 9, 72);
  3112. check(11, 5, 55);
  3113. check(99, 17, 1683);
  3114. }
  3115. #[test]
  3116. fn test_is_even() {
  3117. let one: BigUint = FromStr::from_str("1").unwrap();
  3118. let two: BigUint = FromStr::from_str("2").unwrap();
  3119. let thousand: BigUint = FromStr::from_str("1000").unwrap();
  3120. let big: BigUint = FromStr::from_str("1000000000000000000000").unwrap();
  3121. let bigger: BigUint = FromStr::from_str("1000000000000000000001").unwrap();
  3122. assert!(one.is_odd());
  3123. assert!(two.is_even());
  3124. assert!(thousand.is_even());
  3125. assert!(big.is_even());
  3126. assert!(bigger.is_odd());
  3127. assert!((&one << 64).is_even());
  3128. assert!(((&one << 64) + one).is_odd());
  3129. }
  3130. fn to_str_pairs() -> Vec<(BigUint, Vec<(u32, String)>)> {
  3131. let bits = big_digit::BITS;
  3132. vec!(( Zero::zero(), vec!(
  3133. (2, "0".to_string()), (3, "0".to_string())
  3134. )), ( BigUint::from_slice(&[ 0xff ]), vec!(
  3135. (2, "11111111".to_string()),
  3136. (3, "100110".to_string()),
  3137. (4, "3333".to_string()),
  3138. (5, "2010".to_string()),
  3139. (6, "1103".to_string()),
  3140. (7, "513".to_string()),
  3141. (8, "377".to_string()),
  3142. (9, "313".to_string()),
  3143. (10, "255".to_string()),
  3144. (11, "212".to_string()),
  3145. (12, "193".to_string()),
  3146. (13, "168".to_string()),
  3147. (14, "143".to_string()),
  3148. (15, "120".to_string()),
  3149. (16, "ff".to_string())
  3150. )), ( BigUint::from_slice(&[ 0xfff ]), vec!(
  3151. (2, "111111111111".to_string()),
  3152. (4, "333333".to_string()),
  3153. (16, "fff".to_string())
  3154. )), ( BigUint::from_slice(&[ 1, 2 ]), vec!(
  3155. (2,
  3156. format!("10{}1", repeat("0").take(bits - 1).collect::<String>())),
  3157. (4,
  3158. format!("2{}1", repeat("0").take(bits / 2 - 1).collect::<String>())),
  3159. (10, match bits {
  3160. 32 => "8589934593".to_string(),
  3161. 16 => "131073".to_string(),
  3162. _ => panic!()
  3163. }),
  3164. (16,
  3165. format!("2{}1", repeat("0").take(bits / 4 - 1).collect::<String>()))
  3166. )), ( BigUint::from_slice(&[ 1, 2, 3 ]), vec!(
  3167. (2,
  3168. format!("11{}10{}1",
  3169. repeat("0").take(bits - 2).collect::<String>(),
  3170. repeat("0").take(bits - 1).collect::<String>())),
  3171. (4,
  3172. format!("3{}2{}1",
  3173. repeat("0").take(bits / 2 - 1).collect::<String>(),
  3174. repeat("0").take(bits / 2 - 1).collect::<String>())),
  3175. (8, match bits {
  3176. 32 => "6000000000100000000001".to_string(),
  3177. 16 => "140000400001".to_string(),
  3178. _ => panic!()
  3179. }),
  3180. (10, match bits {
  3181. 32 => "55340232229718589441".to_string(),
  3182. 16 => "12885032961".to_string(),
  3183. _ => panic!()
  3184. }),
  3185. (16,
  3186. format!("3{}2{}1",
  3187. repeat("0").take(bits / 4 - 1).collect::<String>(),
  3188. repeat("0").take(bits / 4 - 1).collect::<String>()))
  3189. )) )
  3190. }
  3191. #[test]
  3192. fn test_to_str_radix() {
  3193. let r = to_str_pairs();
  3194. for num_pair in r.iter() {
  3195. let &(ref n, ref rs) = num_pair;
  3196. for str_pair in rs.iter() {
  3197. let &(ref radix, ref str) = str_pair;
  3198. assert_eq!(n.to_str_radix(*radix), *str);
  3199. }
  3200. }
  3201. }
  3202. #[test]
  3203. fn test_from_str_radix() {
  3204. let r = to_str_pairs();
  3205. for num_pair in r.iter() {
  3206. let &(ref n, ref rs) = num_pair;
  3207. for str_pair in rs.iter() {
  3208. let &(ref radix, ref str) = str_pair;
  3209. assert_eq!(n,
  3210. &BigUint::from_str_radix(str, *radix).unwrap());
  3211. }
  3212. }
  3213. let zed = BigUint::from_str_radix("Z", 10).ok();
  3214. assert_eq!(zed, None);
  3215. let blank = BigUint::from_str_radix("_", 2).ok();
  3216. assert_eq!(blank, None);
  3217. let minus_one = BigUint::from_str_radix("-1", 10).ok();
  3218. assert_eq!(minus_one, None);
  3219. }
  3220. #[test]
  3221. fn test_all_str_radix() {
  3222. use std::ascii::AsciiExt;
  3223. let n = BigUint::new((0..10).collect());
  3224. for radix in 2..37 {
  3225. let s = n.to_str_radix(radix);
  3226. let x = BigUint::from_str_radix(&s, radix);
  3227. assert_eq!(x.unwrap(), n);
  3228. let s = s.to_ascii_uppercase();
  3229. let x = BigUint::from_str_radix(&s, radix);
  3230. assert_eq!(x.unwrap(), n);
  3231. }
  3232. }
  3233. #[test]
  3234. fn test_factor() {
  3235. fn factor(n: usize) -> BigUint {
  3236. let mut f: BigUint = One::one();
  3237. for i in 2..n + 1 {
  3238. // FIXME(#5992): assignment operator overloads
  3239. // f *= FromPrimitive::from_usize(i);
  3240. let bu: BigUint = FromPrimitive::from_usize(i).unwrap();
  3241. f = f * bu;
  3242. }
  3243. return f;
  3244. }
  3245. fn check(n: usize, s: &str) {
  3246. let n = factor(n);
  3247. let ans = match BigUint::from_str_radix(s, 10) {
  3248. Ok(x) => x, Err(_) => panic!()
  3249. };
  3250. assert_eq!(n, ans);
  3251. }
  3252. check(3, "6");
  3253. check(10, "3628800");
  3254. check(20, "2432902008176640000");
  3255. check(30, "265252859812191058636308480000000");
  3256. }
  3257. #[test]
  3258. fn test_bits() {
  3259. assert_eq!(BigUint::new(vec!(0,0,0,0)).bits(), 0);
  3260. let n: BigUint = FromPrimitive::from_usize(0).unwrap();
  3261. assert_eq!(n.bits(), 0);
  3262. let n: BigUint = FromPrimitive::from_usize(1).unwrap();
  3263. assert_eq!(n.bits(), 1);
  3264. let n: BigUint = FromPrimitive::from_usize(3).unwrap();
  3265. assert_eq!(n.bits(), 2);
  3266. let n: BigUint = BigUint::from_str_radix("4000000000", 16).unwrap();
  3267. assert_eq!(n.bits(), 39);
  3268. let one: BigUint = One::one();
  3269. assert_eq!((one << 426).bits(), 427);
  3270. }
  3271. #[test]
  3272. fn test_rand() {
  3273. let mut rng = thread_rng();
  3274. let _n: BigUint = rng.gen_biguint(137);
  3275. assert!(rng.gen_biguint(0).is_zero());
  3276. }
  3277. #[test]
  3278. fn test_rand_range() {
  3279. let mut rng = thread_rng();
  3280. for _ in 0..10 {
  3281. assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_usize(236).unwrap(),
  3282. &FromPrimitive::from_usize(237).unwrap()),
  3283. FromPrimitive::from_usize(236).unwrap());
  3284. }
  3285. let l = FromPrimitive::from_usize(403469000 + 2352).unwrap();
  3286. let u = FromPrimitive::from_usize(403469000 + 3513).unwrap();
  3287. for _ in 0..1000 {
  3288. let n: BigUint = rng.gen_biguint_below(&u);
  3289. assert!(n < u);
  3290. let n: BigUint = rng.gen_biguint_range(&l, &u);
  3291. assert!(n >= l);
  3292. assert!(n < u);
  3293. }
  3294. }
  3295. #[test]
  3296. #[should_panic]
  3297. fn test_zero_rand_range() {
  3298. thread_rng().gen_biguint_range(&FromPrimitive::from_usize(54).unwrap(),
  3299. &FromPrimitive::from_usize(54).unwrap());
  3300. }
  3301. #[test]
  3302. #[should_panic]
  3303. fn test_negative_rand_range() {
  3304. let mut rng = thread_rng();
  3305. let l = FromPrimitive::from_usize(2352).unwrap();
  3306. let u = FromPrimitive::from_usize(3513).unwrap();
  3307. // Switching u and l should fail:
  3308. let _n: BigUint = rng.gen_biguint_range(&u, &l);
  3309. }
  3310. #[test]
  3311. fn test_sub_sign() {
  3312. use super::sub_sign;
  3313. let a = BigInt::from_str_radix("265252859812191058636308480000000", 10).unwrap();
  3314. let b = BigInt::from_str_radix("26525285981219105863630848000000", 10).unwrap();
  3315. assert_eq!(sub_sign(&a.data.data[..], &b.data.data[..]), &a - &b);
  3316. assert_eq!(sub_sign(&b.data.data[..], &a.data.data[..]), &b - &a);
  3317. }
  3318. fn test_mul_divide_torture_count(count: usize) {
  3319. use rand::{SeedableRng, StdRng, Rng};
  3320. let bits_max = 1 << 12;
  3321. let seed: &[_] = &[1, 2, 3, 4];
  3322. let mut rng: StdRng = SeedableRng::from_seed(seed);
  3323. for _ in 0..count {
  3324. /* Test with numbers of random sizes: */
  3325. let xbits = rng.gen_range(0, bits_max);
  3326. let ybits = rng.gen_range(0, bits_max);
  3327. let x = rng.gen_biguint(xbits);
  3328. let y = rng.gen_biguint(ybits);
  3329. if x.is_zero() || y.is_zero() {
  3330. continue;
  3331. }
  3332. let prod = &x * &y;
  3333. assert_eq!(&prod / &x, y);
  3334. assert_eq!(&prod / &y, x);
  3335. }
  3336. }
  3337. #[test]
  3338. fn test_mul_divide_torture() {
  3339. test_mul_divide_torture_count(1000);
  3340. }
  3341. #[test]
  3342. #[ignore]
  3343. fn test_mul_divide_torture_long() {
  3344. test_mul_divide_torture_count(1000000);
  3345. }
  3346. }
  3347. #[cfg(test)]
  3348. mod bigint_tests {
  3349. use Integer;
  3350. use super::{BigDigit, BigUint, ToBigUint};
  3351. use super::{Sign, BigInt, RandBigInt, ToBigInt, big_digit};
  3352. use super::Sign::{Minus, NoSign, Plus};
  3353. use std::cmp::Ordering::{Less, Equal, Greater};
  3354. use std::{f32, f64};
  3355. use std::{i8, i16, i32, i64, isize};
  3356. use std::iter::repeat;
  3357. use std::{u8, u16, u32, u64, usize};
  3358. use std::ops::{Neg};
  3359. use rand::thread_rng;
  3360. use {Zero, One, Signed, ToPrimitive, FromPrimitive, Num};
  3361. use Float;
  3362. /// Assert that an op works for all val/ref combinations
  3363. macro_rules! assert_op {
  3364. ($left:ident $op:tt $right:ident == $expected:expr) => {
  3365. assert_eq!((&$left) $op (&$right), $expected);
  3366. assert_eq!((&$left) $op $right.clone(), $expected);
  3367. assert_eq!($left.clone() $op (&$right), $expected);
  3368. assert_eq!($left.clone() $op $right.clone(), $expected);
  3369. };
  3370. }
  3371. #[test]
  3372. fn test_from_biguint() {
  3373. fn check(inp_s: Sign, inp_n: usize, ans_s: Sign, ans_n: usize) {
  3374. let inp = BigInt::from_biguint(inp_s, FromPrimitive::from_usize(inp_n).unwrap());
  3375. let ans = BigInt { sign: ans_s, data: FromPrimitive::from_usize(ans_n).unwrap()};
  3376. assert_eq!(inp, ans);
  3377. }
  3378. check(Plus, 1, Plus, 1);
  3379. check(Plus, 0, NoSign, 0);
  3380. check(Minus, 1, Minus, 1);
  3381. check(NoSign, 1, NoSign, 0);
  3382. }
  3383. #[test]
  3384. fn test_from_bytes_be() {
  3385. fn check(s: &str, result: &str) {
  3386. assert_eq!(BigInt::from_bytes_be(Plus, s.as_bytes()),
  3387. BigInt::parse_bytes(result.as_bytes(), 10).unwrap());
  3388. }
  3389. check("A", "65");
  3390. check("AA", "16705");
  3391. check("AB", "16706");
  3392. check("Hello world!", "22405534230753963835153736737");
  3393. assert_eq!(BigInt::from_bytes_be(Plus, &[]), Zero::zero());
  3394. assert_eq!(BigInt::from_bytes_be(Minus, &[]), Zero::zero());
  3395. }
  3396. #[test]
  3397. fn test_to_bytes_be() {
  3398. fn check(s: &str, result: &str) {
  3399. let b = BigInt::parse_bytes(result.as_bytes(), 10).unwrap();
  3400. let (sign, v) = b.to_bytes_be();
  3401. assert_eq!((Plus, s.as_bytes()), (sign, &*v));
  3402. }
  3403. check("A", "65");
  3404. check("AA", "16705");
  3405. check("AB", "16706");
  3406. check("Hello world!", "22405534230753963835153736737");
  3407. let b: BigInt = Zero::zero();
  3408. assert_eq!(b.to_bytes_be(), (NoSign, vec![0]));
  3409. // Test with leading/trailing zero bytes and a full BigDigit of value 0
  3410. let b = BigInt::from_str_radix("00010000000000000200", 16).unwrap();
  3411. assert_eq!(b.to_bytes_be(), (Plus, vec![1, 0, 0, 0, 0, 0, 0, 2, 0]));
  3412. }
  3413. #[test]
  3414. fn test_from_bytes_le() {
  3415. fn check(s: &str, result: &str) {
  3416. assert_eq!(BigInt::from_bytes_le(Plus, s.as_bytes()),
  3417. BigInt::parse_bytes(result.as_bytes(), 10).unwrap());
  3418. }
  3419. check("A", "65");
  3420. check("AA", "16705");
  3421. check("BA", "16706");
  3422. check("!dlrow olleH", "22405534230753963835153736737");
  3423. assert_eq!(BigInt::from_bytes_le(Plus, &[]), Zero::zero());
  3424. assert_eq!(BigInt::from_bytes_le(Minus, &[]), Zero::zero());
  3425. }
  3426. #[test]
  3427. fn test_to_bytes_le() {
  3428. fn check(s: &str, result: &str) {
  3429. let b = BigInt::parse_bytes(result.as_bytes(), 10).unwrap();
  3430. let (sign, v) = b.to_bytes_le();
  3431. assert_eq!((Plus, s.as_bytes()), (sign, &*v));
  3432. }
  3433. check("A", "65");
  3434. check("AA", "16705");
  3435. check("BA", "16706");
  3436. check("!dlrow olleH", "22405534230753963835153736737");
  3437. let b: BigInt = Zero::zero();
  3438. assert_eq!(b.to_bytes_le(), (NoSign, vec![0]));
  3439. // Test with leading/trailing zero bytes and a full BigDigit of value 0
  3440. let b = BigInt::from_str_radix("00010000000000000200", 16).unwrap();
  3441. assert_eq!(b.to_bytes_le(), (Plus, vec![0, 2, 0, 0, 0, 0, 0, 0, 1]));
  3442. }
  3443. #[test]
  3444. fn test_cmp() {
  3445. let vs: [&[BigDigit]; 4] = [ &[2 as BigDigit], &[1, 1], &[2, 1], &[1, 1, 1] ];
  3446. let mut nums = Vec::new();
  3447. for s in vs.iter().rev() {
  3448. nums.push(BigInt::from_slice(Minus, *s));
  3449. }
  3450. nums.push(Zero::zero());
  3451. nums.extend(vs.iter().map(|s| BigInt::from_slice(Plus, *s)));
  3452. for (i, ni) in nums.iter().enumerate() {
  3453. for (j0, nj) in nums[i..].iter().enumerate() {
  3454. let j = i + j0;
  3455. if i == j {
  3456. assert_eq!(ni.cmp(nj), Equal);
  3457. assert_eq!(nj.cmp(ni), Equal);
  3458. assert_eq!(ni, nj);
  3459. assert!(!(ni != nj));
  3460. assert!(ni <= nj);
  3461. assert!(ni >= nj);
  3462. assert!(!(ni < nj));
  3463. assert!(!(ni > nj));
  3464. } else {
  3465. assert_eq!(ni.cmp(nj), Less);
  3466. assert_eq!(nj.cmp(ni), Greater);
  3467. assert!(!(ni == nj));
  3468. assert!(ni != nj);
  3469. assert!(ni <= nj);
  3470. assert!(!(ni >= nj));
  3471. assert!(ni < nj);
  3472. assert!(!(ni > nj));
  3473. assert!(!(nj <= ni));
  3474. assert!(nj >= ni);
  3475. assert!(!(nj < ni));
  3476. assert!(nj > ni);
  3477. }
  3478. }
  3479. }
  3480. }
  3481. #[test]
  3482. fn test_hash() {
  3483. let a = BigInt::new(NoSign, vec!());
  3484. let b = BigInt::new(NoSign, vec!(0));
  3485. let c = BigInt::new(Plus, vec!(1));
  3486. let d = BigInt::new(Plus, vec!(1,0,0,0,0,0));
  3487. let e = BigInt::new(Plus, vec!(0,0,0,0,0,1));
  3488. let f = BigInt::new(Minus, vec!(1));
  3489. assert!(::hash(&a) == ::hash(&b));
  3490. assert!(::hash(&b) != ::hash(&c));
  3491. assert!(::hash(&c) == ::hash(&d));
  3492. assert!(::hash(&d) != ::hash(&e));
  3493. assert!(::hash(&c) != ::hash(&f));
  3494. }
  3495. #[test]
  3496. fn test_convert_i64() {
  3497. fn check(b1: BigInt, i: i64) {
  3498. let b2: BigInt = FromPrimitive::from_i64(i).unwrap();
  3499. assert!(b1 == b2);
  3500. assert!(b1.to_i64().unwrap() == i);
  3501. }
  3502. check(Zero::zero(), 0);
  3503. check(One::one(), 1);
  3504. check(i64::MIN.to_bigint().unwrap(), i64::MIN);
  3505. check(i64::MAX.to_bigint().unwrap(), i64::MAX);
  3506. assert_eq!(
  3507. (i64::MAX as u64 + 1).to_bigint().unwrap().to_i64(),
  3508. None);
  3509. assert_eq!(
  3510. BigInt::from_biguint(Plus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_i64(),
  3511. None);
  3512. assert_eq!(
  3513. BigInt::from_biguint(Minus, BigUint::new(vec!(1,0,0,1<<(big_digit::BITS-1)))).to_i64(),
  3514. None);
  3515. assert_eq!(
  3516. BigInt::from_biguint(Minus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_i64(),
  3517. None);
  3518. }
  3519. #[test]
  3520. fn test_convert_u64() {
  3521. fn check(b1: BigInt, u: u64) {
  3522. let b2: BigInt = FromPrimitive::from_u64(u).unwrap();
  3523. assert!(b1 == b2);
  3524. assert!(b1.to_u64().unwrap() == u);
  3525. }
  3526. check(Zero::zero(), 0);
  3527. check(One::one(), 1);
  3528. check(u64::MIN.to_bigint().unwrap(), u64::MIN);
  3529. check(u64::MAX.to_bigint().unwrap(), u64::MAX);
  3530. assert_eq!(
  3531. BigInt::from_biguint(Plus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_u64(),
  3532. None);
  3533. let max_value: BigUint = FromPrimitive::from_u64(u64::MAX).unwrap();
  3534. assert_eq!(BigInt::from_biguint(Minus, max_value).to_u64(), None);
  3535. assert_eq!(BigInt::from_biguint(Minus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_u64(), None);
  3536. }
  3537. #[test]
  3538. fn test_convert_f32() {
  3539. fn check(b1: &BigInt, f: f32) {
  3540. let b2 = BigInt::from_f32(f).unwrap();
  3541. assert_eq!(b1, &b2);
  3542. assert_eq!(b1.to_f32().unwrap(), f);
  3543. let neg_b1 = -b1;
  3544. let neg_b2 = BigInt::from_f32(-f).unwrap();
  3545. assert_eq!(neg_b1, neg_b2);
  3546. assert_eq!(neg_b1.to_f32().unwrap(), -f);
  3547. }
  3548. check(&BigInt::zero(), 0.0);
  3549. check(&BigInt::one(), 1.0);
  3550. check(&BigInt::from(u16::MAX), 2.0.powi(16) - 1.0);
  3551. check(&BigInt::from(1u64 << 32), 2.0.powi(32));
  3552. check(&BigInt::from_slice(Plus, &[0, 0, 1]), 2.0.powi(64));
  3553. check(&((BigInt::one() << 100) + (BigInt::one() << 123)), 2.0.powi(100) + 2.0.powi(123));
  3554. check(&(BigInt::one() << 127), 2.0.powi(127));
  3555. check(&(BigInt::from((1u64 << 24) - 1) << (128 - 24)), f32::MAX);
  3556. // keeping all 24 digits with the bits at different offsets to the BigDigits
  3557. let x: u32 = 0b00000000101111011111011011011101;
  3558. let mut f = x as f32;
  3559. let mut b = BigInt::from(x);
  3560. for _ in 0..64 {
  3561. check(&b, f);
  3562. f *= 2.0;
  3563. b = b << 1;
  3564. }
  3565. // this number when rounded to f64 then f32 isn't the same as when rounded straight to f32
  3566. let mut n: i64 = 0b0000000000111111111111111111111111011111111111111111111111111111;
  3567. assert!((n as f64) as f32 != n as f32);
  3568. assert_eq!(BigInt::from(n).to_f32(), Some(n as f32));
  3569. n = -n;
  3570. assert!((n as f64) as f32 != n as f32);
  3571. assert_eq!(BigInt::from(n).to_f32(), Some(n as f32));
  3572. // test rounding up with the bits at different offsets to the BigDigits
  3573. let mut f = ((1u64 << 25) - 1) as f32;
  3574. let mut b = BigInt::from(1u64 << 25);
  3575. for _ in 0..64 {
  3576. assert_eq!(b.to_f32(), Some(f));
  3577. f *= 2.0;
  3578. b = b << 1;
  3579. }
  3580. // rounding
  3581. assert_eq!(BigInt::from_f32(-f32::consts::PI), Some(BigInt::from(-3i32)));
  3582. assert_eq!(BigInt::from_f32(-f32::consts::E), Some(BigInt::from(-2i32)));
  3583. assert_eq!(BigInt::from_f32(-0.99999), Some(BigInt::zero()));
  3584. assert_eq!(BigInt::from_f32(-0.5), Some(BigInt::zero()));
  3585. assert_eq!(BigInt::from_f32(-0.0), Some(BigInt::zero()));
  3586. assert_eq!(BigInt::from_f32(f32::MIN_POSITIVE / 2.0), Some(BigInt::zero()));
  3587. assert_eq!(BigInt::from_f32(f32::MIN_POSITIVE), Some(BigInt::zero()));
  3588. assert_eq!(BigInt::from_f32(0.5), Some(BigInt::zero()));
  3589. assert_eq!(BigInt::from_f32(0.99999), Some(BigInt::zero()));
  3590. assert_eq!(BigInt::from_f32(f32::consts::E), Some(BigInt::from(2u32)));
  3591. assert_eq!(BigInt::from_f32(f32::consts::PI), Some(BigInt::from(3u32)));
  3592. // special float values
  3593. assert_eq!(BigInt::from_f32(f32::NAN), None);
  3594. assert_eq!(BigInt::from_f32(f32::INFINITY), None);
  3595. assert_eq!(BigInt::from_f32(f32::NEG_INFINITY), None);
  3596. // largest BigInt that will round to a finite f32 value
  3597. let big_num = (BigInt::one() << 128) - BigInt::one() - (BigInt::one() << (128 - 25));
  3598. assert_eq!(big_num.to_f32(), Some(f32::MAX));
  3599. assert_eq!((&big_num + BigInt::one()).to_f32(), None);
  3600. assert_eq!((-&big_num).to_f32(), Some(f32::MIN));
  3601. assert_eq!(((-&big_num) - BigInt::one()).to_f32(), None);
  3602. assert_eq!(((BigInt::one() << 128) - BigInt::one()).to_f32(), None);
  3603. assert_eq!((BigInt::one() << 128).to_f32(), None);
  3604. assert_eq!((-((BigInt::one() << 128) - BigInt::one())).to_f32(), None);
  3605. assert_eq!((-(BigInt::one() << 128)).to_f32(), None);
  3606. }
  3607. #[test]
  3608. fn test_convert_f64() {
  3609. fn check(b1: &BigInt, f: f64) {
  3610. let b2 = BigInt::from_f64(f).unwrap();
  3611. assert_eq!(b1, &b2);
  3612. assert_eq!(b1.to_f64().unwrap(), f);
  3613. let neg_b1 = -b1;
  3614. let neg_b2 = BigInt::from_f64(-f).unwrap();
  3615. assert_eq!(neg_b1, neg_b2);
  3616. assert_eq!(neg_b1.to_f64().unwrap(), -f);
  3617. }
  3618. check(&BigInt::zero(), 0.0);
  3619. check(&BigInt::one(), 1.0);
  3620. check(&BigInt::from(u32::MAX), 2.0.powi(32) - 1.0);
  3621. check(&BigInt::from(1u64 << 32), 2.0.powi(32));
  3622. check(&BigInt::from_slice(Plus, &[0, 0, 1]), 2.0.powi(64));
  3623. check(&((BigInt::one() << 100) + (BigInt::one() << 152)), 2.0.powi(100) + 2.0.powi(152));
  3624. check(&(BigInt::one() << 1023), 2.0.powi(1023));
  3625. check(&(BigInt::from((1u64 << 53) - 1) << (1024 - 53)), f64::MAX);
  3626. // keeping all 53 digits with the bits at different offsets to the BigDigits
  3627. let x: u64 = 0b0000000000011110111110110111111101110111101111011111011011011101;
  3628. let mut f = x as f64;
  3629. let mut b = BigInt::from(x);
  3630. for _ in 0..128 {
  3631. check(&b, f);
  3632. f *= 2.0;
  3633. b = b << 1;
  3634. }
  3635. // test rounding up with the bits at different offsets to the BigDigits
  3636. let mut f = ((1u64 << 54) - 1) as f64;
  3637. let mut b = BigInt::from(1u64 << 54);
  3638. for _ in 0..128 {
  3639. assert_eq!(b.to_f64(), Some(f));
  3640. f *= 2.0;
  3641. b = b << 1;
  3642. }
  3643. // rounding
  3644. assert_eq!(BigInt::from_f64(-f64::consts::PI), Some(BigInt::from(-3i32)));
  3645. assert_eq!(BigInt::from_f64(-f64::consts::E), Some(BigInt::from(-2i32)));
  3646. assert_eq!(BigInt::from_f64(-0.99999), Some(BigInt::zero()));
  3647. assert_eq!(BigInt::from_f64(-0.5), Some(BigInt::zero()));
  3648. assert_eq!(BigInt::from_f64(-0.0), Some(BigInt::zero()));
  3649. assert_eq!(BigInt::from_f64(f64::MIN_POSITIVE / 2.0), Some(BigInt::zero()));
  3650. assert_eq!(BigInt::from_f64(f64::MIN_POSITIVE), Some(BigInt::zero()));
  3651. assert_eq!(BigInt::from_f64(0.5), Some(BigInt::zero()));
  3652. assert_eq!(BigInt::from_f64(0.99999), Some(BigInt::zero()));
  3653. assert_eq!(BigInt::from_f64(f64::consts::E), Some(BigInt::from(2u32)));
  3654. assert_eq!(BigInt::from_f64(f64::consts::PI), Some(BigInt::from(3u32)));
  3655. // special float values
  3656. assert_eq!(BigInt::from_f64(f64::NAN), None);
  3657. assert_eq!(BigInt::from_f64(f64::INFINITY), None);
  3658. assert_eq!(BigInt::from_f64(f64::NEG_INFINITY), None);
  3659. // largest BigInt that will round to a finite f64 value
  3660. let big_num = (BigInt::one() << 1024) - BigInt::one() - (BigInt::one() << (1024 - 54));
  3661. assert_eq!(big_num.to_f64(), Some(f64::MAX));
  3662. assert_eq!((&big_num + BigInt::one()).to_f64(), None);
  3663. assert_eq!((-&big_num).to_f64(), Some(f64::MIN));
  3664. assert_eq!(((-&big_num) - BigInt::one()).to_f64(), None);
  3665. assert_eq!(((BigInt::one() << 1024) - BigInt::one()).to_f64(), None);
  3666. assert_eq!((BigInt::one() << 1024).to_f64(), None);
  3667. assert_eq!((-((BigInt::one() << 1024) - BigInt::one())).to_f64(), None);
  3668. assert_eq!((-(BigInt::one() << 1024)).to_f64(), None);
  3669. }
  3670. #[test]
  3671. fn test_convert_to_biguint() {
  3672. fn check(n: BigInt, ans_1: BigUint) {
  3673. assert_eq!(n.to_biguint().unwrap(), ans_1);
  3674. assert_eq!(n.to_biguint().unwrap().to_bigint().unwrap(), n);
  3675. }
  3676. let zero: BigInt = Zero::zero();
  3677. let unsigned_zero: BigUint = Zero::zero();
  3678. let positive = BigInt::from_biguint(
  3679. Plus, BigUint::new(vec!(1,2,3)));
  3680. let negative = -&positive;
  3681. check(zero, unsigned_zero);
  3682. check(positive, BigUint::new(vec!(1,2,3)));
  3683. assert_eq!(negative.to_biguint(), None);
  3684. }
  3685. #[test]
  3686. fn test_convert_from_uint() {
  3687. macro_rules! check {
  3688. ($ty:ident, $max:expr) => {
  3689. assert_eq!(BigInt::from($ty::zero()), BigInt::zero());
  3690. assert_eq!(BigInt::from($ty::one()), BigInt::one());
  3691. assert_eq!(BigInt::from($ty::MAX - $ty::one()), $max - BigInt::one());
  3692. assert_eq!(BigInt::from($ty::MAX), $max);
  3693. }
  3694. }
  3695. check!(u8, BigInt::from_slice(Plus, &[u8::MAX as BigDigit]));
  3696. check!(u16, BigInt::from_slice(Plus, &[u16::MAX as BigDigit]));
  3697. check!(u32, BigInt::from_slice(Plus, &[u32::MAX as BigDigit]));
  3698. check!(u64, BigInt::from_slice(Plus, &[u32::MAX as BigDigit, u32::MAX as BigDigit]));
  3699. check!(usize, BigInt::from(usize::MAX as u64));
  3700. }
  3701. #[test]
  3702. fn test_convert_from_int() {
  3703. macro_rules! check {
  3704. ($ty:ident, $min:expr, $max:expr) => {
  3705. assert_eq!(BigInt::from($ty::MIN), $min);
  3706. assert_eq!(BigInt::from($ty::MIN + $ty::one()), $min + BigInt::one());
  3707. assert_eq!(BigInt::from(-$ty::one()), -BigInt::one());
  3708. assert_eq!(BigInt::from($ty::zero()), BigInt::zero());
  3709. assert_eq!(BigInt::from($ty::one()), BigInt::one());
  3710. assert_eq!(BigInt::from($ty::MAX - $ty::one()), $max - BigInt::one());
  3711. assert_eq!(BigInt::from($ty::MAX), $max);
  3712. }
  3713. }
  3714. check!(i8, BigInt::from_slice(Minus, &[1 << 7]),
  3715. BigInt::from_slice(Plus, &[i8::MAX as BigDigit]));
  3716. check!(i16, BigInt::from_slice(Minus, &[1 << 15]),
  3717. BigInt::from_slice(Plus, &[i16::MAX as BigDigit]));
  3718. check!(i32, BigInt::from_slice(Minus, &[1 << 31]),
  3719. BigInt::from_slice(Plus, &[i32::MAX as BigDigit]));
  3720. check!(i64, BigInt::from_slice(Minus, &[0, 1 << 31]),
  3721. BigInt::from_slice(Plus, &[u32::MAX as BigDigit, i32::MAX as BigDigit]));
  3722. check!(isize, BigInt::from(isize::MIN as i64),
  3723. BigInt::from(isize::MAX as i64));
  3724. }
  3725. #[test]
  3726. fn test_convert_from_biguint() {
  3727. assert_eq!(BigInt::from(BigUint::zero()), BigInt::zero());
  3728. assert_eq!(BigInt::from(BigUint::one()), BigInt::one());
  3729. assert_eq!(BigInt::from(BigUint::from_slice(&[1, 2, 3])), BigInt::from_slice(Plus, &[1, 2, 3]));
  3730. }
  3731. const N1: BigDigit = -1i32 as BigDigit;
  3732. const N2: BigDigit = -2i32 as BigDigit;
  3733. const SUM_TRIPLES: &'static [(&'static [BigDigit],
  3734. &'static [BigDigit],
  3735. &'static [BigDigit])] = &[
  3736. (&[], &[], &[]),
  3737. (&[], &[ 1], &[ 1]),
  3738. (&[ 1], &[ 1], &[ 2]),
  3739. (&[ 1], &[ 1, 1], &[ 2, 1]),
  3740. (&[ 1], &[N1], &[ 0, 1]),
  3741. (&[ 1], &[N1, N1], &[ 0, 0, 1]),
  3742. (&[N1, N1], &[N1, N1], &[N2, N1, 1]),
  3743. (&[ 1, 1, 1], &[N1, N1], &[ 0, 1, 2]),
  3744. (&[ 2, 2, 1], &[N1, N2], &[ 1, 1, 2])
  3745. ];
  3746. #[test]
  3747. fn test_add() {
  3748. for elm in SUM_TRIPLES.iter() {
  3749. let (a_vec, b_vec, c_vec) = *elm;
  3750. let a = BigInt::from_slice(Plus, a_vec);
  3751. let b = BigInt::from_slice(Plus, b_vec);
  3752. let c = BigInt::from_slice(Plus, c_vec);
  3753. let (na, nb, nc) = (-&a, -&b, -&c);
  3754. assert_op!(a + b == c);
  3755. assert_op!(b + a == c);
  3756. assert_op!(c + na == b);
  3757. assert_op!(c + nb == a);
  3758. assert_op!(a + nc == nb);
  3759. assert_op!(b + nc == na);
  3760. assert_op!(na + nb == nc);
  3761. assert_op!(a + na == Zero::zero());
  3762. }
  3763. }
  3764. #[test]
  3765. fn test_sub() {
  3766. for elm in SUM_TRIPLES.iter() {
  3767. let (a_vec, b_vec, c_vec) = *elm;
  3768. let a = BigInt::from_slice(Plus, a_vec);
  3769. let b = BigInt::from_slice(Plus, b_vec);
  3770. let c = BigInt::from_slice(Plus, c_vec);
  3771. let (na, nb, nc) = (-&a, -&b, -&c);
  3772. assert_op!(c - a == b);
  3773. assert_op!(c - b == a);
  3774. assert_op!(nb - a == nc);
  3775. assert_op!(na - b == nc);
  3776. assert_op!(b - na == c);
  3777. assert_op!(a - nb == c);
  3778. assert_op!(nc - na == nb);
  3779. assert_op!(a - a == Zero::zero());
  3780. }
  3781. }
  3782. const M: u32 = ::std::u32::MAX;
  3783. static MUL_TRIPLES: &'static [(&'static [BigDigit],
  3784. &'static [BigDigit],
  3785. &'static [BigDigit])] = &[
  3786. (&[], &[], &[]),
  3787. (&[], &[ 1], &[]),
  3788. (&[ 2], &[], &[]),
  3789. (&[ 1], &[ 1], &[1]),
  3790. (&[ 2], &[ 3], &[ 6]),
  3791. (&[ 1], &[ 1, 1, 1], &[1, 1, 1]),
  3792. (&[ 1, 2, 3], &[ 3], &[ 3, 6, 9]),
  3793. (&[ 1, 1, 1], &[N1], &[N1, N1, N1]),
  3794. (&[ 1, 2, 3], &[N1], &[N1, N2, N2, 2]),
  3795. (&[ 1, 2, 3, 4], &[N1], &[N1, N2, N2, N2, 3]),
  3796. (&[N1], &[N1], &[ 1, N2]),
  3797. (&[N1, N1], &[N1], &[ 1, N1, N2]),
  3798. (&[N1, N1, N1], &[N1], &[ 1, N1, N1, N2]),
  3799. (&[N1, N1, N1, N1], &[N1], &[ 1, N1, N1, N1, N2]),
  3800. (&[ M/2 + 1], &[ 2], &[ 0, 1]),
  3801. (&[0, M/2 + 1], &[ 2], &[ 0, 0, 1]),
  3802. (&[ 1, 2], &[ 1, 2, 3], &[1, 4, 7, 6]),
  3803. (&[N1, N1], &[N1, N1, N1], &[1, 0, N1, N2, N1]),
  3804. (&[N1, N1, N1], &[N1, N1, N1, N1], &[1, 0, 0, N1, N2, N1, N1]),
  3805. (&[ 0, 0, 1], &[ 1, 2, 3], &[0, 0, 1, 2, 3]),
  3806. (&[ 0, 0, 1], &[ 0, 0, 0, 1], &[0, 0, 0, 0, 0, 1])
  3807. ];
  3808. static DIV_REM_QUADRUPLES: &'static [(&'static [BigDigit],
  3809. &'static [BigDigit],
  3810. &'static [BigDigit],
  3811. &'static [BigDigit])]
  3812. = &[
  3813. (&[ 1], &[ 2], &[], &[1]),
  3814. (&[ 1, 1], &[ 2], &[ M/2+1], &[1]),
  3815. (&[ 1, 1, 1], &[ 2], &[ M/2+1, M/2+1], &[1]),
  3816. (&[ 0, 1], &[N1], &[1], &[1]),
  3817. (&[N1, N1], &[N2], &[2, 1], &[3])
  3818. ];
  3819. #[test]
  3820. fn test_mul() {
  3821. for elm in MUL_TRIPLES.iter() {
  3822. let (a_vec, b_vec, c_vec) = *elm;
  3823. let a = BigInt::from_slice(Plus, a_vec);
  3824. let b = BigInt::from_slice(Plus, b_vec);
  3825. let c = BigInt::from_slice(Plus, c_vec);
  3826. let (na, nb, nc) = (-&a, -&b, -&c);
  3827. assert_op!(a * b == c);
  3828. assert_op!(b * a == c);
  3829. assert_op!(na * nb == c);
  3830. assert_op!(na * b == nc);
  3831. assert_op!(nb * a == nc);
  3832. }
  3833. for elm in DIV_REM_QUADRUPLES.iter() {
  3834. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  3835. let a = BigInt::from_slice(Plus, a_vec);
  3836. let b = BigInt::from_slice(Plus, b_vec);
  3837. let c = BigInt::from_slice(Plus, c_vec);
  3838. let d = BigInt::from_slice(Plus, d_vec);
  3839. assert!(a == &b * &c + &d);
  3840. assert!(a == &c * &b + &d);
  3841. }
  3842. }
  3843. #[test]
  3844. fn test_div_mod_floor() {
  3845. fn check_sub(a: &BigInt, b: &BigInt, ans_d: &BigInt, ans_m: &BigInt) {
  3846. let (d, m) = a.div_mod_floor(b);
  3847. if !m.is_zero() {
  3848. assert_eq!(m.sign, b.sign);
  3849. }
  3850. assert!(m.abs() <= b.abs());
  3851. assert!(*a == b * &d + &m);
  3852. assert!(d == *ans_d);
  3853. assert!(m == *ans_m);
  3854. }
  3855. fn check(a: &BigInt, b: &BigInt, d: &BigInt, m: &BigInt) {
  3856. if m.is_zero() {
  3857. check_sub(a, b, d, m);
  3858. check_sub(a, &b.neg(), &d.neg(), m);
  3859. check_sub(&a.neg(), b, &d.neg(), m);
  3860. check_sub(&a.neg(), &b.neg(), d, m);
  3861. } else {
  3862. let one: BigInt = One::one();
  3863. check_sub(a, b, d, m);
  3864. check_sub(a, &b.neg(), &(d.neg() - &one), &(m - b));
  3865. check_sub(&a.neg(), b, &(d.neg() - &one), &(b - m));
  3866. check_sub(&a.neg(), &b.neg(), d, &m.neg());
  3867. }
  3868. }
  3869. for elm in MUL_TRIPLES.iter() {
  3870. let (a_vec, b_vec, c_vec) = *elm;
  3871. let a = BigInt::from_slice(Plus, a_vec);
  3872. let b = BigInt::from_slice(Plus, b_vec);
  3873. let c = BigInt::from_slice(Plus, c_vec);
  3874. if !a.is_zero() { check(&c, &a, &b, &Zero::zero()); }
  3875. if !b.is_zero() { check(&c, &b, &a, &Zero::zero()); }
  3876. }
  3877. for elm in DIV_REM_QUADRUPLES.iter() {
  3878. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  3879. let a = BigInt::from_slice(Plus, a_vec);
  3880. let b = BigInt::from_slice(Plus, b_vec);
  3881. let c = BigInt::from_slice(Plus, c_vec);
  3882. let d = BigInt::from_slice(Plus, d_vec);
  3883. if !b.is_zero() {
  3884. check(&a, &b, &c, &d);
  3885. }
  3886. }
  3887. }
  3888. #[test]
  3889. fn test_div_rem() {
  3890. fn check_sub(a: &BigInt, b: &BigInt, ans_q: &BigInt, ans_r: &BigInt) {
  3891. let (q, r) = a.div_rem(b);
  3892. if !r.is_zero() {
  3893. assert_eq!(r.sign, a.sign);
  3894. }
  3895. assert!(r.abs() <= b.abs());
  3896. assert!(*a == b * &q + &r);
  3897. assert!(q == *ans_q);
  3898. assert!(r == *ans_r);
  3899. let (a, b, ans_q, ans_r) = (a.clone(), b.clone(), ans_q.clone(), ans_r.clone());
  3900. assert_op!(a / b == ans_q);
  3901. assert_op!(a % b == ans_r);
  3902. }
  3903. fn check(a: &BigInt, b: &BigInt, q: &BigInt, r: &BigInt) {
  3904. check_sub(a, b, q, r);
  3905. check_sub(a, &b.neg(), &q.neg(), r);
  3906. check_sub(&a.neg(), b, &q.neg(), &r.neg());
  3907. check_sub(&a.neg(), &b.neg(), q, &r.neg());
  3908. }
  3909. for elm in MUL_TRIPLES.iter() {
  3910. let (a_vec, b_vec, c_vec) = *elm;
  3911. let a = BigInt::from_slice(Plus, a_vec);
  3912. let b = BigInt::from_slice(Plus, b_vec);
  3913. let c = BigInt::from_slice(Plus, c_vec);
  3914. if !a.is_zero() { check(&c, &a, &b, &Zero::zero()); }
  3915. if !b.is_zero() { check(&c, &b, &a, &Zero::zero()); }
  3916. }
  3917. for elm in DIV_REM_QUADRUPLES.iter() {
  3918. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  3919. let a = BigInt::from_slice(Plus, a_vec);
  3920. let b = BigInt::from_slice(Plus, b_vec);
  3921. let c = BigInt::from_slice(Plus, c_vec);
  3922. let d = BigInt::from_slice(Plus, d_vec);
  3923. if !b.is_zero() {
  3924. check(&a, &b, &c, &d);
  3925. }
  3926. }
  3927. }
  3928. #[test]
  3929. fn test_checked_add() {
  3930. for elm in SUM_TRIPLES.iter() {
  3931. let (a_vec, b_vec, c_vec) = *elm;
  3932. let a = BigInt::from_slice(Plus, a_vec);
  3933. let b = BigInt::from_slice(Plus, b_vec);
  3934. let c = BigInt::from_slice(Plus, c_vec);
  3935. assert!(a.checked_add(&b).unwrap() == c);
  3936. assert!(b.checked_add(&a).unwrap() == c);
  3937. assert!(c.checked_add(&(-&a)).unwrap() == b);
  3938. assert!(c.checked_add(&(-&b)).unwrap() == a);
  3939. assert!(a.checked_add(&(-&c)).unwrap() == (-&b));
  3940. assert!(b.checked_add(&(-&c)).unwrap() == (-&a));
  3941. assert!((-&a).checked_add(&(-&b)).unwrap() == (-&c));
  3942. assert!(a.checked_add(&(-&a)).unwrap() == Zero::zero());
  3943. }
  3944. }
  3945. #[test]
  3946. fn test_checked_sub() {
  3947. for elm in SUM_TRIPLES.iter() {
  3948. let (a_vec, b_vec, c_vec) = *elm;
  3949. let a = BigInt::from_slice(Plus, a_vec);
  3950. let b = BigInt::from_slice(Plus, b_vec);
  3951. let c = BigInt::from_slice(Plus, c_vec);
  3952. assert!(c.checked_sub(&a).unwrap() == b);
  3953. assert!(c.checked_sub(&b).unwrap() == a);
  3954. assert!((-&b).checked_sub(&a).unwrap() == (-&c));
  3955. assert!((-&a).checked_sub(&b).unwrap() == (-&c));
  3956. assert!(b.checked_sub(&(-&a)).unwrap() == c);
  3957. assert!(a.checked_sub(&(-&b)).unwrap() == c);
  3958. assert!((-&c).checked_sub(&(-&a)).unwrap() == (-&b));
  3959. assert!(a.checked_sub(&a).unwrap() == Zero::zero());
  3960. }
  3961. }
  3962. #[test]
  3963. fn test_checked_mul() {
  3964. for elm in MUL_TRIPLES.iter() {
  3965. let (a_vec, b_vec, c_vec) = *elm;
  3966. let a = BigInt::from_slice(Plus, a_vec);
  3967. let b = BigInt::from_slice(Plus, b_vec);
  3968. let c = BigInt::from_slice(Plus, c_vec);
  3969. assert!(a.checked_mul(&b).unwrap() == c);
  3970. assert!(b.checked_mul(&a).unwrap() == c);
  3971. assert!((-&a).checked_mul(&b).unwrap() == -&c);
  3972. assert!((-&b).checked_mul(&a).unwrap() == -&c);
  3973. }
  3974. for elm in DIV_REM_QUADRUPLES.iter() {
  3975. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  3976. let a = BigInt::from_slice(Plus, a_vec);
  3977. let b = BigInt::from_slice(Plus, b_vec);
  3978. let c = BigInt::from_slice(Plus, c_vec);
  3979. let d = BigInt::from_slice(Plus, d_vec);
  3980. assert!(a == b.checked_mul(&c).unwrap() + &d);
  3981. assert!(a == c.checked_mul(&b).unwrap() + &d);
  3982. }
  3983. }
  3984. #[test]
  3985. fn test_checked_div() {
  3986. for elm in MUL_TRIPLES.iter() {
  3987. let (a_vec, b_vec, c_vec) = *elm;
  3988. let a = BigInt::from_slice(Plus, a_vec);
  3989. let b = BigInt::from_slice(Plus, b_vec);
  3990. let c = BigInt::from_slice(Plus, c_vec);
  3991. if !a.is_zero() {
  3992. assert!(c.checked_div(&a).unwrap() == b);
  3993. assert!((-&c).checked_div(&(-&a)).unwrap() == b);
  3994. assert!((-&c).checked_div(&a).unwrap() == -&b);
  3995. }
  3996. if !b.is_zero() {
  3997. assert!(c.checked_div(&b).unwrap() == a);
  3998. assert!((-&c).checked_div(&(-&b)).unwrap() == a);
  3999. assert!((-&c).checked_div(&b).unwrap() == -&a);
  4000. }
  4001. assert!(c.checked_div(&Zero::zero()).is_none());
  4002. assert!((-&c).checked_div(&Zero::zero()).is_none());
  4003. }
  4004. }
  4005. #[test]
  4006. fn test_gcd() {
  4007. fn check(a: isize, b: isize, c: isize) {
  4008. let big_a: BigInt = FromPrimitive::from_isize(a).unwrap();
  4009. let big_b: BigInt = FromPrimitive::from_isize(b).unwrap();
  4010. let big_c: BigInt = FromPrimitive::from_isize(c).unwrap();
  4011. assert_eq!(big_a.gcd(&big_b), big_c);
  4012. }
  4013. check(10, 2, 2);
  4014. check(10, 3, 1);
  4015. check(0, 3, 3);
  4016. check(3, 3, 3);
  4017. check(56, 42, 14);
  4018. check(3, -3, 3);
  4019. check(-6, 3, 3);
  4020. check(-4, -2, 2);
  4021. }
  4022. #[test]
  4023. fn test_lcm() {
  4024. fn check(a: isize, b: isize, c: isize) {
  4025. let big_a: BigInt = FromPrimitive::from_isize(a).unwrap();
  4026. let big_b: BigInt = FromPrimitive::from_isize(b).unwrap();
  4027. let big_c: BigInt = FromPrimitive::from_isize(c).unwrap();
  4028. assert_eq!(big_a.lcm(&big_b), big_c);
  4029. }
  4030. check(1, 0, 0);
  4031. check(0, 1, 0);
  4032. check(1, 1, 1);
  4033. check(-1, 1, 1);
  4034. check(1, -1, 1);
  4035. check(-1, -1, 1);
  4036. check(8, 9, 72);
  4037. check(11, 5, 55);
  4038. }
  4039. #[test]
  4040. fn test_abs_sub() {
  4041. let zero: BigInt = Zero::zero();
  4042. let one: BigInt = One::one();
  4043. assert_eq!((-&one).abs_sub(&one), zero);
  4044. let one: BigInt = One::one();
  4045. let zero: BigInt = Zero::zero();
  4046. assert_eq!(one.abs_sub(&one), zero);
  4047. let one: BigInt = One::one();
  4048. let zero: BigInt = Zero::zero();
  4049. assert_eq!(one.abs_sub(&zero), one);
  4050. let one: BigInt = One::one();
  4051. let two: BigInt = FromPrimitive::from_isize(2).unwrap();
  4052. assert_eq!(one.abs_sub(&-&one), two);
  4053. }
  4054. #[test]
  4055. fn test_from_str_radix() {
  4056. fn check(s: &str, ans: Option<isize>) {
  4057. let ans = ans.map(|n| {
  4058. let x: BigInt = FromPrimitive::from_isize(n).unwrap();
  4059. x
  4060. });
  4061. assert_eq!(BigInt::from_str_radix(s, 10).ok(), ans);
  4062. }
  4063. check("10", Some(10));
  4064. check("1", Some(1));
  4065. check("0", Some(0));
  4066. check("-1", Some(-1));
  4067. check("-10", Some(-10));
  4068. check("Z", None);
  4069. check("_", None);
  4070. // issue 10522, this hit an edge case that caused it to
  4071. // attempt to allocate a vector of size (-1u) == huge.
  4072. let x: BigInt =
  4073. format!("1{}", repeat("0").take(36).collect::<String>()).parse().unwrap();
  4074. let _y = x.to_string();
  4075. }
  4076. #[test]
  4077. fn test_neg() {
  4078. assert!(-BigInt::new(Plus, vec!(1, 1, 1)) ==
  4079. BigInt::new(Minus, vec!(1, 1, 1)));
  4080. assert!(-BigInt::new(Minus, vec!(1, 1, 1)) ==
  4081. BigInt::new(Plus, vec!(1, 1, 1)));
  4082. let zero: BigInt = Zero::zero();
  4083. assert_eq!(-&zero, zero);
  4084. }
  4085. #[test]
  4086. fn test_rand() {
  4087. let mut rng = thread_rng();
  4088. let _n: BigInt = rng.gen_bigint(137);
  4089. assert!(rng.gen_bigint(0).is_zero());
  4090. }
  4091. #[test]
  4092. fn test_rand_range() {
  4093. let mut rng = thread_rng();
  4094. for _ in 0..10 {
  4095. assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_usize(236).unwrap(),
  4096. &FromPrimitive::from_usize(237).unwrap()),
  4097. FromPrimitive::from_usize(236).unwrap());
  4098. }
  4099. fn check(l: BigInt, u: BigInt) {
  4100. let mut rng = thread_rng();
  4101. for _ in 0..1000 {
  4102. let n: BigInt = rng.gen_bigint_range(&l, &u);
  4103. assert!(n >= l);
  4104. assert!(n < u);
  4105. }
  4106. }
  4107. let l: BigInt = FromPrimitive::from_usize(403469000 + 2352).unwrap();
  4108. let u: BigInt = FromPrimitive::from_usize(403469000 + 3513).unwrap();
  4109. check( l.clone(), u.clone());
  4110. check(-l.clone(), u.clone());
  4111. check(-u.clone(), -l.clone());
  4112. }
  4113. #[test]
  4114. #[should_panic]
  4115. fn test_zero_rand_range() {
  4116. thread_rng().gen_bigint_range(&FromPrimitive::from_isize(54).unwrap(),
  4117. &FromPrimitive::from_isize(54).unwrap());
  4118. }
  4119. #[test]
  4120. #[should_panic]
  4121. fn test_negative_rand_range() {
  4122. let mut rng = thread_rng();
  4123. let l = FromPrimitive::from_usize(2352).unwrap();
  4124. let u = FromPrimitive::from_usize(3513).unwrap();
  4125. // Switching u and l should fail:
  4126. let _n: BigInt = rng.gen_bigint_range(&u, &l);
  4127. }
  4128. }